本文介绍了HttpClient 4.0.1 - 如何释放连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一堆 URL 进行了循环,对于每个 URL,我正在执行以下操作:

I have a loop over a bunch of URLs, for each one I'm doing the following:

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

}

第一个查询没问题,第二个抛出这个异常:

The first query is fine, the second throws this exception:

线程main"中的异常java.lang.IllegalStateException:无效使用SingleClientConnManager:连接仍然分配.确保释放分配前的连接另一个.在org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:199)在org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:173)......

这只是一个简单的单线程应用程序.我怎样才能解除这个连接?

This is just a simple single-threaded app. How can I release this connection?

推荐答案

要回答我自己的问题:要释放连接(以及与请求关联的任何其他资源),您必须关闭 HttpEntity 返回的 InputStream:

To answer my own question: to release the connection (and any other resources associated with the request) you must close the InputStream returned by the HttpEntity:

InputStream is = entity.getContent();

.... process the input stream ....

is.close();       // releases all resources

来自 文档

这篇关于HttpClient 4.0.1 - 如何释放连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 06:48