释放 HttpClient 4.1.x 的连接以使用一个 HttpClient 实例顺序执行
Posted
技术标签:
【中文标题】释放 HttpClient 4.1.x 的连接以使用一个 HttpClient 实例顺序执行【英文标题】:Releasing connection of HttpClient 4.1.x for sequential execution with one HttpClient instance 【发布时间】:2011-08-19 10:53:56 【问题描述】:我很抱歉有点重复,here,here,但他们说,如果您读取响应正文的最后一个字节并关闭输入流。它已准备好接受另一个请求。但是看看我在这里得到了什么,执行新请求时总是会出现这个错误。
SingleClientConnManager 使用无效:连接仍然分配
public String detectGooglePost(String text) throws SystemException
List<NameValuePair> qParams = new ArrayList<NameValuePair>();
qParams.add(new BasicNameValuePair("key", key));
List<NameValuePair> bodyParams = new ArrayList<NameValuePair>();
bodyParams.add(new BasicNameValuePair("q", text));
HttpPost httpPost = new HttpPost(createURI(qParams));
httpPost.addHeader("X-HTTP-Method-Override", "GET");
try
httpPost.setEntity(new UrlEncodedFormEntity(bodyParams));
catch (UnsupportedEncodingException e)
throw new SystemException("Problem when buidling Google request entity", e);
String language = getLanguage(httpPost);
return language;
private String getLanguage(HttpUriRequest request) throws SystemException
HttpResponse response;
try
response = httpclient.execute(request);
catch (Exception e)
throw new SystemException("Problem when executing Google request", e);
int sc = response.getStatusLine().getStatusCode();
if (sc != HttpStatus.SC_OK)
throw new SystemException("google status code : " + sc);
StringBuilder builder = getBuilder(response);
String language = processJson(builder.toString());
return language;
private StringBuilder getBuilder(HttpResponse response) throws SystemException
HttpEntity entity = response.getEntity();
if (entity == null)
throw new SystemException("response entity null");
StringBuilder builder = new StringBuilder();
BufferedReader in = null;
String str;
try
in = new BufferedReader(new InputStreamReader(entity.getContent()));
while ((str = in.readLine()) != null)
builder.append(str);
catch (IOException e)
throw new SystemException("Reading input stream of http google response entity problem", e);
finally
IOUtils.closeQuietly(in);
if (builder.length() == 0)
throw new SystemException("content stream of response entity empty has zero length");
return builder;
我应该如何释放连接?流被读取并关闭。但是当再次调用 detectGooglePost(text) 方法(单例 HttpClient 实例)时,仍然会抛出该错误。
【问题讨论】:
【参考方案1】:它必须有效,试试这个:
HttpResponse response;
String responseBody;
try
response = httpclient.execute(request);
int sc = response.getStatusLine().getStatusCode();
if (sc != HttpStatus.SC_OK)
throw new SystemException("google status code : " + sc);
HttpEntity entity = response.getEntity();
if (entity == null)
throw new SystemException("response entity null");
responseBody = EntityUtils.toString(entity);
catch (Exception e)
request.abort();
throw new SystemException("Problem when executing Google request", e);
【讨论】:
以上是关于释放 HttpClient 4.1.x 的连接以使用一个 HttpClient 实例顺序执行的主要内容,如果未能解决你的问题,请参考以下文章
HttpClient 4.0.1 - 如何释放连接? [复制]
HttpClient在响应流完全读取之前被释放,导致连接关闭异常