HttpClient 4.0.1-如何释放连接?
我遍历了一堆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
}
第一个查询很好,第二个查询抛出此异常:
线程“主”中的异常java.lang.IllegalStateException:无效使用SingleClientConnManager:仍然分配了连接。在分配另一个之前,请确保释放连接。在org.apache.http.impl.conn.SingleClientConnManager。$
1.getConnection(SingleClientConnManager.java:173)上的org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:199)…
这只是一个简单的单线程应用程序。如何释放此连接?
回答:
要回答我自己的问题:要释放连接(以及与请求关联的任何其他资源),必须关闭HttpEntity返回的InputStream:
InputStream is = entity.getContent();.... process the input stream ....
is.close();       // releases all resources
来自文档
以上是 HttpClient 4.0.1-如何释放连接? 的全部内容, 来源链接: utcz.com/qa/400969.html






