HttpClient
一个支持HTTP协议的高效java编程工具包
可以实现所有HTTP的方法
当我们调用其他系统的基于HTTP的接口时使用
eg:微信支付,查看高德地图,查看短信验证码等
核心API
HttpClient:
Http客户端对象,通过对象发起Http请求
HttpClients:
构建器,用于获得HttpClient对象
CloseableHttpClient:
具体的实现类,实现了HttpClient接口
HttpGet:
Get方式请求
HttpPost:
Post方式请求
引入maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
HTTPClient调用Get请求
//创建httpClient对象
CloseableHttpClient httpClients = HttpClients.createDefault();
//创建一个Get请求对象,访问指定的路径
HttpGet getRequest = new HttpGet(url);
//发送请求对象得到响应结果
CloseableHttpResponse response = httpClients.execute(getRequest);
response属性:
response.statusLine().statusCode() 状态行.HTTP状态码
response.getEntity() 响应体
response.getHeader 响应头
HTTPClient调用Post请求
//创建httpClient对象
CloseableHttpClient httpClients = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost("url");
//创建JSONObject参数实体类 requestPojo
//在请求体中添加属性
requestPojo.put()
//创建请求实体类
StringEntity entity = new StringEntity(requestPojo.toString());
//指定编码方式
entity.setContentEncoding("utf-8");
//指定数据格式
entity.setContentType("application/json");
//设置请求体
httpPost.setEntity(entity);
//发起请求,获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
//response属性同get请求