HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
1.导入依赖
<!-- httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2.发送get请求
@Test
public void test() throws IOException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建get请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求,接受响应结果
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
//解析响应结果
//获取响应码
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码是"+statusCode);
//获取响应体
HttpEntity entity = httpResponse.getEntity();
String string = EntityUtils.toString(entity);
System.out.println("响应体是"+string);
//关闭资源
httpClient.close();
httpResponse.close();
}
3.发送post请求
@Test
public void testpost() throws IOException, JSONException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建post请求对象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//创建json对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
//设置请求参数
StringEntity stringEntity = new StringEntity(jsonObject.toString());
//指定编码方式
stringEntity.setContentType("UTF-8");
//指定数据格式
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
//发送请求,接受响应结果
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
//解析响应结果
//获取响应码
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码是"+statusCode);
//获取响应体
HttpEntity entity = httpResponse.getEntity();
String string = EntityUtils.toString(entity);
System.out.println("响应体是"+string);
//关闭资源
httpClient.close();
httpResponse.close();
}
心得:
jsonObject可以创建json对象,使用put方式添加元素。