HttpClient
HttpClient可以用来提供高效的,最新的,功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议
就是在java中可以模拟客户端发送请求
其中通过几个核心的API完成功能:
HttpClient
,HttpClients
,CloseableHttpClient
,HttpGet
,HttpPost
使用
第一步:导入依赖
<dependency>
<groupId>org.apache.httpcomponents<groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
其中CloseableHttpClient是HttpClient的实现类,HttpClient是一个接口
- 发送GET方式请求的步骤
- 创建HttpClient对象
- 创建Http请求对象
- 调用HttpClient的execute方法发送请求
@Test
public void test() throws Exception{
//创建HttpClient对象
//其中CloseableHttpClient是HttpClient的实现类,HttpClient是一个接口
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求
CloseableHttpResponse execute = httpClient.execute(httpGet);
//获取服务端返回的状态码
int statusCode = execute.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码:"+statusCode);
//获取数据实体
HttpEntity entity = execute.getEntity();
//整合到了自带的数据实体中,我们可以通过HttpEntityUtils进行解析
String string = EntityUtils.toString(entity);
System.out.println("服务端返回的数据为"+string);
//关闭资源
execute.close();
httpClient.close();
}
- 发送POST请求方式的步骤
- 创建HttpClient对象
- 创建Http请求对象
- 调用HttpClient的execute方法发送请求
@Test
public void testpost() throws Exception{
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
//创建请求体,利用阿里巴巴的fastjson
JSONObject jsonObject=new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//将创建的json数据引入到Entity对象当中去
StringEntity entity=new StringEntity(jsonObject.toString());
httpPost.setEntity(entity);
//指定传进来的请求的编码方式
entity.setContentEncoding("utf-8");
//指定传输的数据格式,指定传过来的请求是json格式,后端才能够进行解析
entity.setContentType("application/json");
//发送请求
CloseableHttpResponse execute = httpClient.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();
httpClient.close();
}