开源库—HttpClient:ConnectionPoolTimeoutException

抛出ConnectionPoolTimeoutException的原因?

不管接口是否返回200,reponse里的entity都需要被消费,否则entity里的流不会关闭,造成连接泄露,抛出ConnectionPoolTimeoutException异常。

解决方法

接口返回200,正常获取返回的entity,如果没有返回200,使用EntityUtils.consumeQuietly(response.getEntity())消费reponse里的entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private String executeMethod(HttpUriRequest request) throws IOException {
if (this.headers != null && this.headers.size() > 0) {
for (Map.Entry<String, String> entry : this.headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
HttpClient httpClient = HttpConnectionManager.getInst().getHttpClient();
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity, DEFAULT_CHARSET_NAME) : null;
} else {
//状态不是200的时候reponse的流也要消费一下,否则连接不会返回连接池,导致连接泄露
EntityUtils.consumeQuietly(response.getEntity());
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
------ 本文完 ------