一、概述
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient的作用有俩个:
简单的说,可以将HttpClient理解为一个虚拟的网络客户端,可以在java程序中模拟发送Http请求和接收响应,也就是在程序中模拟平常正常用浏览器上网发送请求给服务器这一行为。
-
发送HTTP请求
通过编码定义HTTP请求,包括请求的方法(如GET、POST等)、URL、请求头、请求体等信息。 -
发送HTTP请求
服务器对HttpClient发出的请求做出响应,HttpClient库可以接收这个响应,并允许你的程序解析响应数据,如状态码、响应体等。
二、使用
使用HttpClient首先要引入它的maven坐标:
HttpClient的Maven坐标:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
HttpClient发送请求的步骤:
-
创建HttpClient对象
-
创建Http请求对象
-
调用HttpClient的execute方法发送请求
示例(Get请求方式):
/**
* 测试通过httpclient发送GET方式的请求
*/
@Test
public void testGET() throws Exception{
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080"); //要访问的地址
//发送请求,接受响应结果
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码为:" + statusCode);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
System.out.println("服务端返回的数据为:" + body);
//关闭资源
response.close();
httpClient.close();
Post请求方式示例:
// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//创建设置请求参数,封装为json字符串
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
StringEntity entity = new StringEntity(jsonObject.toString());
//指定请求编码方式
entity.setContentEncoding("utf-8");
//数据格式
entity.setContentType("application/json");
httpPost.setEntity(entity);
//发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//解析返回结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("响应码为:" + statusCode);
HttpEntity entity1 = response.getEntity();
String body = EntityUtils.toString(entity1);
System.out.println("响应数据为:" + body);
//关闭资源
response.close();
httpClient.close();
HttpClient的常用API介绍:
1. 创建 HttpClient
创建 HttpClient 对象可以通过静态工厂方法 newHttpClient()
进行创建。
HttpClient client = HttpClient.newHttpClient();
也可以使用 HttpClient.Builder
来进行更多配置:
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2) // 使用HTTP/2
.followRedirects(HttpClient.Redirect.NORMAL) // 设置重定向策略
.build();
2. 创建 HttpRequest
创建 HttpRequest 对象来定义和发送请求。
- GET 请求:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/data"))
.build();
- POST 请求:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/data"))
.header("Content-Type", "application/json") // 设置请求头
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"user\"}")) // 设置请求体
.build();
3. 发送请求
使用 HttpClient 发送请求并获取响应:
- 同步发送请求:
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
- 异步发送请求:
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
4. 处理响应
HttpResponse 对象中包含了响应的全部信息,包括状态码、响应头和响应体。
- 获取响应状态码:
int statusCode = response.statusCode();
System.out.println("状态码: " + statusCode);
- 获取响应头:
HttpHeaders headers = response.headers();
headers.map().forEach((k, v) -> System.out.println(k + ":" + v));
- 获取响应体:
String responseBody = response.body();
System.out.println("响应体: " + responseBody);
5. 设置请求超时
可以通过 HttpRequest.Builder
设置请求的超时时间:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/data"))
.timeout(Duration.ofMinutes(2)) // 设置超时时间为 2 分钟
.build();
6. 处理表单数据
HttpClient 也可以用于发送表单数据:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/form"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString("param1=value1¶m2=value2"))
.build();
7. 处理文件上传
如果需要上传文件,可以使用 HttpRequest.BodyPublishers.ofFile()
:
Path filePath = Paths.get("path/to/file.txt");
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/upload"))
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofFile(filePath))
.build();