获取HttpClient链接:
CloseableHttpClient client = HttpClients.createDefault();
创建get请求对象:
String url = "http://www.dianping.com/searchads/ajax/recads/baby?cityId=1";
HttpGet httpGet = new HttpGet(url);
设置请求超时时间(setConnectTimeout----请求服务器连接超时,setSocketTimeout--从服务器获取数据超时):
RequestConfig reuestConfig = RequestConfig.custom()
.setConnectTimeout(timeout)
.setSocketTimeout(timeout).build();
httpGet.setConfig(reuestConfig);
设置请求cookie:
httpGet.addHeader("Cookie","key=value");
……
执行请求,获取响应:
CloseableHttpResponse response = client.execute(httpGet);
获取响应状态码:
response.getStatusLine().getStatusCode()
获取返回结果,并转化成字符串:
HttpEntity entity = response.getEntity();
String returnValue = EntityUtils.toString(entity);
遇到的问题:
1.循环执行请求时,从第3个get请求开始就会阻塞
HttpClient httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
for(int i=269268;i<269300;i++){
String url = "http://****.com/rule/baby-tag/ruleEditor/getRuleStr?ruleItemID=" + i;
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Cookie", "sso_clientId=****");
HttpResponse httpResponse = httpClient.execute(httpGet);
httpResponse.getEntity().getContent().close();
System.out.println(httpResponse.getStatusLine().getStatusCode()+":"+i);
}
原因:由于没有关闭response中的InputStream流,所以连接一直没有释放,而连接池中默认最大路由连接数为2,所以第3个请求开始出现阻塞。
解决方式:关闭InputStream流,如下
EntityUtils.toString(httpResponse.getEntity());
或者
httpResponse.getEntity().getContent().close();
2.连接池(PoolingHttpClientConnectionManager)和客户端(CloseableHttpClient)之间的关系。
连接池可以设置最大连接数和每条路由最大连接数,正常情况下,我们只需要一个client对应一个连接池,如问题1中,单个client路由请求达到2之后阻塞。
其实也可以多个client使用同一个连接池(连接池路由最大数为2),证明如下:
CloseableHttpClient build = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
CloseableHttpClient build1 = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
String url = "http://****.com/rule/baby-tag/ruleEditor/getRuleStr?ruleItemID=269441";
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Cookie", "sso_clientId=***");
HttpResponse httpResponse1 = build.execute(httpGet); //1
HttpResponse httpResponse11 = build1.execute(httpGet); //2
HttpResponse httpResponse2 = build.execute(httpGet); //3
build和build1各发送了一个请求,并且没有关闭流,因此请求3会被阻塞
3.怎么判断连接池中的连接是否正在使用,或者空闲还是被销毁?