我对一堆 URL 进行了循环,对于每个 URL,我都在执行以下操作:
private String doQuery(String url) {
HttpGet httpGet = new HttpGet(url);
setDefaultHeaders(httpGet); // static method
HttpResponse response = httpClient.execute(httpGet); // httpClient instantiated in constructor
int rc = response.getStatusLine().getStatusCode();
if (rc != 200) {
// some stuff...
return;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
// some stuff...
return;
}
// process the entity, get input stream etc
}
第一个查询没问题,第二个抛出这个异常:
Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated. Make sure to release the connection before allocating another one. at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:199) at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:173)......
这只是一个简单的单线程应用程序。如何释放此连接?
最佳答案
Httpcomponents 4.1 推荐的方法是关闭连接并释放任何底层资源:
EntityUtils.consume(HttpEntity)
其中 HttpEntity
传递的是响应实体。
关于java - HttpClient 4.0.1 - 如何释放连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4775618/