一. HttpClient
介绍
HttpClient是Apache Jakarta Common下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
该项目导入了阿里的sdk,传递依赖
核心API:
- HttpClient
- HttpClients
- CloseableHttpClient
- HttpGet
- HttpPost
发生请求步骤:
- 创建HttpClient对象
- 创建Http请求对象
- 调用HttpClient的execute方法发送请求
入门案例
HttpClientTest.java
java
package com.sky.test;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class HttpClientTest {
/**
* 测试HttpClient发送get请求
*/
@Test
public void testGet() {
// 创建HttpClient对象
CloseableHttpClient aDefault = HttpClients.createDefault();
// 创建HttpGet对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
// 发送请求
try {
CloseableHttpResponse execute = aDefault.execute(httpGet);
// 获取响应数据
int statusCode = execute.getStatusLine().getStatusCode();
System.out.println("状态码:" + statusCode);
HttpEntity entity = execute.getEntity();
String string = EntityUtils.toString(entity);
System.out.println("响应数据:" + string);
// 关闭资源
execute.close();
aDefault.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试HttpClient发送post请求
*/
@Test
public void testPost() throws Exception {
// 创建HttpClient对象
CloseableHttpClient aDefault = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
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 execute = aDefault.execute(httpPost);
// 获取响应数据
int statusCode = execute.getStatusLine().getStatusCode();
System.out.println("状态码:" + statusCode);
HttpEntity entity1 = execute.getEntity();
String string = EntityUtils.toString(entity1);
System.out.println("响应数据:" + string);
// 关闭资源
execute.close();
aDefault.close();
}
}