十三、HttpClient
HttpClient是Apache Jakarta Common下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。简单来说就是可以在java中构建HTTP请求。
核心API:核心API:HttpClient、HttpClients、CloseableHttpClient、HttpGet、HttpPost
发请求步骤:①发送请求步骤、②创建HttpClient对象、③调用HttpClient的execute方法发送请求
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
@Test
void testHttpClientGet() throws Exception {
//1、创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//2、创建HttpGet对象,设置url地址
String url = "http://localhost:9091/user/shop/status";
HttpGet get = new HttpGet(url);
//3、使用HttpClient发送请求,获取response
CloseableHttpResponse response = client.execute(get);
System.out.println("响应状态码:"+response.getStatusLine().getStatusCode()); //响应状态码
HttpEntity entity = response.getEntity(); //获取响应体
String body= EntityUtils.toString(entity); //转换为字符串
System.out.println("响应数据:"+body);
//4、关闭资源
response.close();
client.close();
}
@Test
void testHttpClientPost() throws Exception{
//1、创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//2、创建HttpPost对象,设置url地址
String url = "http://localhost:9091/admin/login";
HttpPost post = new HttpPost(url);
//3、设置请求参数
JSONObject employee = new JSONObject(); //封装请求参数
employee.put("username","admin");
employee.put("password","123456");
StringEntity entity =new StringEntity(employee.toString());
//设置请求头和数据类型指定编码
entity.setContentType("application/json");
entity.setContentEncoding("utf-8");
post.setEntity(entity);
//4、使用HttpClient发送请求,获取response
CloseableHttpResponse response = client.execute(post);
//5、解析响应,返回结果
System.out.println("响应状态码:"+response.getStatusLine().getStatusCode());
HttpEntity body =response.getEntity();
String result = EntityUtils.toString(body); //转换为字符串
System.out.println("响应结果:"+result);
//6、关闭资源
response.close();
client.close();
}