HttpClient介绍
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
maven坐标
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
核心API:
- HttpClient
- HttpClients
- CloseableHttpClient : HttpClient的实现类
- HttpGet
- HttpPost
发送请求步骤:
- 创建HttpClient对象
- 创建Http请求对象
- 调用HttpClient的execute方法发送请求
测试代码:
@SpringBootTest
public class HttpClientTest {
/**
* 测试通过httpclient发送GET方式请求
*/
@Test
public void testGET() throws IOException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求, 接收响应结果
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码为:" + statusCode);
//获取响应体
HttpEntity httpEntity = response.getEntity();
String body = EntityUtils.toString(httpEntity);
System.out.println("服务端返回的数据为:" + body);
//关闭资源
response.close();
httpClient.close();
}
/**
* 测试通过httpclient发送POST方式的请求
*/
@Test
public void testPost() throws IOException, JSONException {
//创建httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
//指定请求编码方式
stringEntity.setContentEncoding("utf-8");
//数据格式
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
//发送请求, 接收响应结果
CloseableHttpResponse response = httpclient.execute(httpPost);
//获取状态码
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();
}
}