HTTP Components Logo
超文本传输协议(HTTP)可能是当今互联网上最重要的协议之一,Web 服务、微服务以及支持网络的各种设备上的服务几乎都是 HTTP 协议,HTTP 协议已经从 Web 浏览器走向了更广泛的使用场景。
虽然 java.net
包已经提供了 HTTP 访问资源的基本功能,但是它不够灵活,而且不能随心所欲的进行自定义。Apache HttpClient 5 是一个开源的 HTTP 工具包,可以支持最新 HTTP 协议标准,且有丰富的 API 和强大的扩展特性,可以用于构建任何需要进行 HTTP 协议处理的应用程序。
这篇文章介绍 Apache HttpClient 5 中最为常见的一些用法,通过这篇文章可以快速的入门使用 HttpClient 5,主要内容包括 HttpClient 5 的 Get 请求、Post 请求、如何携带参数、JSON 参数、设置超时、异步请求、操作 Cookie、表单登录、基本认证、Digest 认证以及自定义 HTTP 请求拦截器等。
HttpClient 5 依赖
HttpClient 5 Maven 依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5-fluent -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-fluent</artifactId>
<version>5.1.3</version>
</dependency>
HttpClient 5 Gradle 依赖
implementation 'org.apache.httpcomponents.client5:httpclient5:5.1.3'
implementation 'org.apache.httpcomponents.client5:httpclient5-fluent:5.1.3'
HttpClient 5 GET 请求
package com.wdbyte.httpclient;
import java.io.IOException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
/**
* @author https://www.wdbyte.com
*/
public class HttpClient5Get {
public static void main(String[] args) {
String result = get("http://httpbin.org/get");
System.out.println(result);
}
public static String get(String url) {
String resultContent = null;
HttpGet httpGet = new HttpGet(url);
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
// 获取状态码
System.out.println(response.getVersion()); // HTTP/1.1
System.out.println(response.getCode()); // 200
System.out.println(response.getReasonPhrase()); // OK
HttpEntity entity = response.getEntity();
// 获取响应信息
resultContent = EntityUtils.toString(entity);
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return resultContent;
}
}
响应信息:
HTTP/1.1
200
OK
{
"args": {},
"headers": {
"Accept-Encoding": "gzip, x-gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/5.1.3 (Java/17)",
"X-Amzn-Trace-Id": "Root=1-62bb1891-5ab5e5376ed960471bf32f17"
},
"origin": "47.251.4.198",
"url": "http://httpbin.org/get"
}
HttpClient 5 Fluent GET
使用 Apache HttpClient 5 提供的 Fluent API 可以更便捷的发起 GET 请求,但是可操作的地方较少。
依赖:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5-fluent -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-fluent</artifactId>
<version>5.1.3</version>
</dependency>
示例:
package com.wdbyte.httpclient;
import java.io.IOException;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.client5.http.fluent.Response;
/**
* @author https://www.wdbyte.com
*/
public class HttpClient5GetFluent {
public static void main(String[] args) {
System.out.println(get("http://httpbin.org/get"));
}
public static String get(String url) {
String result = null;
try {
Response response = Request.get(url).execute();
result = response.returnContent().asString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
输出信息:
{
"args": {},
"headers": {
"Accept-Encoding": "gzip, x-gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/5.1.3 (Java/17)",
"X-Amzn-Trace-Id": "Root=1-62bb190e-1ba46a92645843a04c55da32"
},
"origin": "47.251.4.198",
"url": "http://httpbin.org/get"
}
HttpClient5 GET 请求参数
使用 URIBuilder
的 addParameters()
方法来构建 GET 请求的参数。
package com.wdbyte.httpclient;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;
/**
* @author https://www.wdbyte.com
*/
public class HttpClient5GetParams {
public static void main(String[] args) {
String result = get("http://httpbin.org/get");
System.out.println(result);
}
public static String get(String url) {
String resultContent = null;
HttpGet httpGet = new HttpGet(url);
// 表单参数
List<NameValuePair> nvps = new ArrayList<>();
// GET 请求参数
nvps.add(new BasicNameValuePair("username", "wdbyte.com"));
nvps.add(new BasicNameValuePair("password", "secret"));
// 增加到请求 URL 中
try {
URI uri = new URIBuilder(new URI(url))
.addParameters(nvps)
.build();
httpGet.setUri(uri);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
// 获取状态码
System.out.println(response.getVersion()); // HTTP/1.1
System.out.println(response.getCode()); // 200
System.out.println(response.getReasonPhrase()); // OK
HttpEntity entity = response.getEntity();
// 获取响应信息
resultContent = EntityUtils.toString(entity);
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return resultContent;
}
}
输出信息:
{
"args": {
"password": "secret",
"username": "wdbyte.com"
},
"headers": {
"Accept-Encoding": "gzip, x-gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/5.1.3 (Java/1.8.0_151)",
"X-Amzn-Trace-Id": "Root=1-62ecc660-69d58a226aefb1b6226541ec"
},
"origin": "42.120.75.185",
"url": "http://httpbin.org/get?username=wdbyte.com&password=secret"
}
下面是通过抓包得到的请求响应信息格式:
// 请求信息
GET /get?username=wdbyte.com&password=secret HTTP/1.1
Accept-Encoding: gzip, x-gzip, deflate
Host: httpbin.org
Connection: keep-alive
User-Agent: Apache-HttpClient/5.1.3 (Java/1.8.0_151)
// 响应信息
HTTP/1.1 200 OK
Date: Fri, 05 Aug 2022 07:27:30 GMT
Content-Type: application/json
Content-Length: 405
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"args": {
"password": "secret",
"username": "wdbyte.com"
},
"headers": {
"Accept-Encoding": "gzip, x-gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/5.1.3 (Java/1.8.0_151)",
"X-Amzn-Trace-Id": "Root=1-62ecc660-69d58a226aefb1b6226541ec"
},
"origin": "42.120.75.185",
"url": "http://httpbin.org/get?username=wdbyte.com&password=secret"
}
HttpClient 5 POST 请求
下面演示发起一个 POST 请求,并携带表单参数。
参数:username=wdbyte.com&password=secret
package com.wdbyte.httpclient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
/**
* @author https://www.wdbyte.com
*/
public class HttpClient5Post {
public static void main(String[] args) {
String result = post("http://httpbin.org/post");
System