HttpClient 是 客户端编程工具包。能够用来构造发送Http请求。当我们需要客户端发送http请求时(例如微信登入,请求微信登入的接口),就会用到它。
在java中使用HttpClient需要导入他的依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
核心API
- HttpClient(接口)
- HttpClients (用来构建HttpClient)
- CloseableHttpClient(实现类)
- HttpGet
- HttpPost
发送请求步骤
1.创建HttpClient对象
CloseableHttpClient httpclient=HttpClients.createDefault();
2.创建Http请求对象 3.调用HttpClient的excute方法发送请求
get请求
HttpGet httpget =new HttpGet("url");
CloseableHttpResponse response=httpClient.excute(httpGet);
post请求
HttpPost httpPost =new HttpPost("url");
StringEntity entity=new StringEntity(json格式数据);
HttpPost.setEntity(entity);//设置请求参数
CloseableHttpResponse response=httpClient.excute(httpGet);
4.获取服务端返回的数据
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码为:"+statusCode);
HttpEntity entity = response.getEntity();//获取响应数据对象
String body = EntityUtils.toString(entity);
System.out.println("服务端返回的数据为:"+body);
5.关闭资源
//关闭资源
response.close();
httpClient.close();