![HttpClient徽标](https://mkyong.com/wp-content/uploads/2019/10/httpclient-logo.png)
本文向您展示如何使用Apache HttpClient发送HTTP GET / POST请求,JSON,身份验证,超时,重定向以及一些常用示例。
PS已通过HttpClient 4.5.10测试
pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
1.发送GET请求
1.1手动关闭。
HttpClientExample1_1.java
package com.mkyong.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample1_1 {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet request = new HttpGet("https://httpbin.org/get");
// add request headers
request.addHeader("custom-key", "mkyong");
request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");
CloseableHttpResponse response = httpClient.execute(request);
try {
// Get HttpResponse Status
System.out.println(response.getProtocolVersion()); // HTTP/1.1
System.out.println(response.getStatusLine().getStatusCode()); // 200
System.out.println(response.getStatusLine().getReasonPhrase()); // OK
System.out.println(response.getStatusLine().toString()); // HTTP/1.1 200 OK
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
1.2使用try-with-resources结束。
HttpClientExample1_2.java
package com.mkyong.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample1_2 {
public static void main(String[] args) throws IOException {
HttpGet request = new HttpGet("https://httpbin.org/get");
// add request headers
request.addHeader("custom-key", "mkyong");
request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
// Get HttpResponse Status
System.out.println(response.getProtocolVersion()); // HTTP/1.1
System.out.println(response.getStatusLine().getStatusCode()); // 200
System.out.println(response.getStatusLine().getReasonPhrase()); // OK
System.out.println(response.getStatusLine().toString()); // HTTP/1.1 200 OK
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
}
}
2.发送普通的POST请求
HttpClientExample2_1.java
package com.mkyong.http;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class HttpClientExample2_1 {
public static void main(String[] args) {
try {
String result = sendPOST("https://httpbin.org/post");
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String sendPOST(String url) throws IOException {
String result = "";
HttpPost post = new HttpPost(url);
// add request parameters or form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", "abc"));
urlParameters.add(new BasicNameValuePair("password", "123"));
urlParameters.add(new BasicNameValuePair("custom", "secret"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)){
result = EntityUtils.toString(response.getEntity());
}
return result;
}
}
3.发送JSON POST请求
3.1使用JSON格式的数据发送POST请求。 密钥将JSON格式的日期传递到StringEntity
。
HttpClientExample3_1.java
package com.mkyong.http;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample3_1 {
public static void main(String[] args) {
try {
String result = sendPOST("https://httpbin.org/post");
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String sendPOST(String url) throws IOException {
String result = "";
HttpPost post = new HttpPost(url);
StringBuilder json = new StringBuilder();
json.append("{");
json.append("\"name\":\"mkyong\",");
json.append("\"notes\":\"hello\"");
json.append("}");
// send a JSON data
post.setEntity(new StringEntity(json.toString()));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
result = EntityUtils.toString(response.getEntity());
}
return result;
}
}
3.2向Cloudflare API发送POST请求以阻止IP地址。 标头中的身份验证。
HttpClientExample3_2.java
package com.mkyong.http;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample3_2 {
public static void main(String[] args) {
try {
String result = blockIP("1.1.1.1");
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String blockIP(String ip) throws IOException {
String result = "";
HttpPost post = new HttpPost("https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules");
post.addHeader("content-type", "application/json");
post.addHeader("X-Auth-Email", "email");
post.addHeader("X-Auth-Key", "token123");
String block = "{\"target\":\"ip\",\"value\":\"" + ip + "\"}";
StringBuilder entity = new StringBuilder();
entity.append("{");
entity.append("\"mode\":\"block\",");
entity.append("\"configuration\":" + block + ",");
entity.append("\"notes\":\"hello\"");
entity.append("}");
// send a JSON data
post.setEntity(new StringEntity(entity.toString()));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
result = EntityUtils.toString(response.getEntity());
}
return result;
}
}
4. HTTP基本认证
HttpClientExample4_1.java
package com.mkyong.http;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample4_1 {
public static void main(String[] args) throws IOException {
HttpGet request = new HttpGet("http://localhost:8080/books");
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("user", "password")
);
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build();
CloseableHttpResponse response = httpClient.execute(request)) {
// 401 if wrong user/password
System.out.println(response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
}
}
阅读本文– Apache HttpClient基本身份验证示例
5.常见问题
5.1禁用重定向。
HttpClientExample5_1.java
package com.mkyong.customer;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample5_1 {
public static void main(String[] args) throws IOException {
HttpGet request = new HttpGet("https://t.co/calv72DH8f");
request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");
try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
CloseableHttpResponse response = httpClient.execute(request)) {
// Get HttpResponse Status
System.out.println(response.getProtocolVersion()); // HTTP/1.1
System.out.println(response.getStatusLine().getStatusCode()); // 301
System.out.println(response.getStatusLine().getReasonPhrase()); // Moved Permanently
System.out.println(response.getStatusLine().toString()); // HTTP/1.1 301 Moved Permanently
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
}
}
5.2连接超时在请求级别。
HttpGet request = new HttpGet("https://httpbin.org/get");
// 5 seconds timeout
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
request.setConfig(requestConfig);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
//...
}
5.3连接超时在客户端级别。
HttpGet request = new HttpGet("https://httpbin.org/get");
// 5 seconds timeout
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
//request.setConfig(requestConfig);
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.build();
CloseableHttpResponse response = httpClient.execute(request)) {
//...
}
5.4配置代理服务器。 阅读HttpClient代理配置
HttpGet request = new HttpGet("https://httpbin.org/get");
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(new HttpHost("company.proxy.url", 8080))
.build();
request.setConfig(requestConfig);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
//...
}
5.5打开cookie。 读取HTTP Cookie
HttpGet request = new HttpGet("https://httpbin.org/get");
RequestConfig requestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.build();
request.setConfig(requestConfig);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
//...
}
5.6获取响应头以及媒体类型。
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
Header headers = entity.getContentType();
System.out.println(headers);
//...
}
样品
Content-Type: application/json
{
"args": {},
"headers": {
"Accept-Encoding": "gzip,deflate",
"Custom-Key": "mkyong",
"Host": "httpbin.org",
"User-Agent": "Googlebot"
},
"origin": "202.168.71.227, 202.168.71.227",
"url": "https://httpbin.org/get"
}