在这篇文章中,将向你展示四种发送Http的GET/POST的例子,如下:
一、Java 11 HttpClient
在Java11的java.net.http.*包中,有一个HttpClient类可以完成HTTP请求。
Java11HttpClientExample.java
package com.lyl.http;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class Java11HttpClientExample {
private final HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
public static void main(String[] args) throws Exception {
Java11HttpClientExample obj = new Java11HttpClientExample();
System.out.println("测试1:发送Http GET 请求");
obj.sendGet();
System.out.println("测试2:发送Http POST 请求");
obj.sendPost();
}
private void sendGet() throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("你请求数据的url地址"))
.setHeader("User-Agent", "Java 11 HttpClient Bot")
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
private void sendPost() throws Exception {
Map<Object, Object> data = new HashMap<>();
data.put("username", "lyl");
data.put("password", "123");
HttpRequest request = HttpRequest.newBuilder()
.POST(buildFormDataFromMap(data))
.uri(URI.create("你请求数据的url地址"))
.setHeader("User-Agent", "Java 11 HttpClient Bot")
.header("Content-Type", "application/x-www-form-urlencoded")
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
private static HttpRequest.BodyPublisher buildFormDataFromMap(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if (builder.length() > 0) {
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
System.out.println(builder.toString());
return HttpRequest.BodyPublishers.ofString(builder.toString());
}
}
二、Java原生HttpURLConnection
本例使用HttpURLConnection(http)和HttpsURLConnection(https)
HttpURLConnectionExample.java
package com.lyl;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("测试1:发送Http GET 请求");
http.sendGet();
System.out.println("\n测试2:发送 Http POST 请求");
http.sendPost();
}
// HTTP GET请求
private void sendGet() throws Exception {
String url = "你请求数据的url地址";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//默认值GET
con.setRequestMethod("GET");
//添加请求头
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\n发送 'GET' 请求到 URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//打印结果
System.out.println(response.toString());
}
// HTTP POST请求
private void sendPost() throws Exception {
String url = "你请求数据的url地址";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//添加请求头
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//url传参的参数
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
//发送Post请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\n发送 POST 请求到 URL : " + url);
System.out.println("Post 参数 : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//打印结果
System.out.println(response.toString());
}
}
三、Apache HttpClient
使用Apache HttpClient完成HTTP请求的发送需要添加Maven依赖,添加方式如下:
pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
HttpClientExample.java
package com.lyl.http;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HttpClientExample {
private final CloseableHttpClient httpClient = HttpClients.createDefault();
public static void main(String[] args) throws Exception {
HttpClientExample obj = new HttpClientExample();
try {
System.out.println("测试1:发送Http GET 请求");
obj.sendGet();
System.out.println("测试2:发送Http POST 请求");
obj.sendPost();
} finally {
obj.close();
}
}
private void close() throws IOException {
httpClient.close();
}
private void sendGet() throws Exception {
HttpGet request = new HttpGet("你请求数据的url地址");
request.addHeader("custom-key", "lyl");
request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");
try (CloseableHttpResponse response = httpClient.execute(request)) {
System.out.println(response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
Header headers = entity.getContentType();
System.out.println(headers);
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
}
private void sendPost() throws Exception {
HttpPost post = new HttpPost("你请求数据的url地址");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", "lyl"));
urlParameters.add(new BasicNameValuePair("password", "123"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
四、OkHttp
OkHttp在安卓上非常受欢迎,并广泛应用于许多网络项目中。
pom.xml文章来源:https://www.toymoban.com/news/detail-647056.html
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.2</version>
</dependency>
OkHttpExample.java文章来源地址https://www.toymoban.com/news/detail-647056.html
package com.lyl.http;
import okhttp3.*;
import java.io.IOException;
public class OkHttpExample {
private final OkHttpClient httpClient = new OkHttpClient();
public static void main(String[] args) throws Exception {
OkHttpExample obj = new OkHttpExample();
System.out.println("测试1:发送Http GET 请求");
obj.sendGet();
System.out.println("测试2:发送Http POST 请求");
obj.sendPost();
}
private void sendGet() throws Exception {
Request request = new Request.Builder()
.url("你请求数据的url地址")
.addHeader("custom-key", "lyl") // add request headers
.addHeader("User-Agent", "OkHttp Bot")
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
private void sendPost() throws Exception {
RequestBody formBody = new FormBody.Builder()
.add("username", "lyl")
.add("password", "123")
.build();
Request request = new Request.Builder()
.url("你请求数据的url地址")
.addHeader("User-Agent", "OkHttp Bot")
.post(formBody)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
}
到了这里,关于Java发送HTTP GET/POST请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!