一、介绍
HttpClient相比传统JDK自带的HttpURLConnection,从使用上(get/post等请求)、功能上(支持连接池)、以及扩展性(多种组件实现)都更胜一筹。HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。因此,掌握Apache Jakarta Common的HttpClient对系统的性能上提升有很大帮助。
二、使用及示例
2.1、引入jar
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<!-- <version>4.5.9</version> -->
<version>xxx</version>
</dependency>
2.2、定义HttpClient的连接池管理器
/**
* 定义httpClient线程池管理器
* @return
*/
@Bean
public HttpClientConnectionManager poolingConnectionManager() {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(1000);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(5000);
poolingHttpClientConnectionManager.setValidateAfterInactivity(30000);
return poolingHttpClientConnectionManager;
}
2.3、定义RequestConfig设置各种超时时间
@Bean
public RequestConfig requestConfig(){
RequestConfig requestConfig = RequestConfig.custom()
//从连接池中获取连接的超时时间
.setConnectionRequestTimeout(2000)
//与目标服务器连接的时间
.setConnectTimeout(2000)
//socket读数据超时时间:从服务器获取响应数据的超时时间
.setSocketTimeout(200).build();
return requestConfig;
}
2.3、初始化HttpClient的实现类
@Bean
public CloseableHttpClient httpClient(){
CloseableHttpClient httpClient = HttpClientBuilder.create()
//设置连接池中最大连接数
.setMaxConnTotal(1000)
//单个路由最大的连接数
.setMaxConnPerRoute(200)
//使用连接池
.setConnectionManager(poolingConnectionManager())
//使用超时参数配置
.setDefaultRequestConfig(requestConfig()).build();
return httpClient;
}
备注:CloseableHttpClient实现了HttpClient接口。
2.4、使用示例
@Autowired
private HttpClient httpClient;
@Test
public void test02(){
String url = "http://localhost:8081/test/login";
CarOnLineDTO info = new CarOnLineDTO();
info.setCompanyId("1");
info.setLicenseId("341203199210053136");
info.setVehicleNo("浙B81KK5");
info.setLoginTime(20200623211825L);
info.setLongitude(121314489);
info.setLatitude(29766730);
info.setEncrypt((byte) 2);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("traceId", UUID.randomUUID().toString());
httpPost.setHeader("content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
try {
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(info), "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
String string = EntityUtils.toString(httpResponse.getEntity());
CommonResponse commonResponse = JSONObject.parseObject(string, CommonResponse.class);
System.out.println("结果:" + JSONObject.toJSONString(httpResponse.getStatusLine()) + ", commonResponse:" + JSONObject.toJSONString(commonResponse));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2.5、模拟被调用的方法
/**
* 模拟登录
*
* @param object object
* @return ResponseBean
*
* 备注:
* produces是指定返回值类型,比如赋值:"application/json;charset=UTF-8",可以指定多个类型
* consumes只指定请求指定类型,比如赋值:"application/json;charset=UTF-8",可以指定多个类型
*/
@PostMapping(value = "login", consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseBean handle(@RequestBody JSONObject object) throws InterruptedException {
Thread.sleep(5000L);
return new ResponseBean(200, "success");
}