关闭后HttpEntity重置并抛出java.net.SocketException

时间:2015-03-24 09:13:10

标签: java apache-httpclient-4.x

  public static String sendRequest(UUICRequest requset) throws
      ClientProtocolException, IOException
  {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    HttpGet httpGet = new HttpGet(requset.toUrl());
    CloseableHttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    response.close();
    httpClient.close();
    return EntityUtils.toString(entity, "UTF-8");
  }

抛出java.net.SocketException: socket closed

我逐行调试并运行了这个程序,只是在执行时发现entity已更改:

    response.close();
    httpClient.close();

所以我重写了我的代码:

  public static String sendRequest(UUICRequest requset) throws
      ClientProtocolException, IOException
  {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    HttpGet httpGet = new HttpGet(requset.toUrl());
    CloseableHttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    String ret = EntityUtils.toString(entity, "UTF-8");//+
    response.close();
    httpClient.close();
    return ret;//M
  }

此代码按预期工作并成功结束。

我的问题是,为什么httpclient会在关闭entityresponse后重置httpClient

1 个答案:

答案 0 :(得分:4)

  

我的问题是,为什么httpclient会在关闭响应和httpClient后重置实体?

流式HTTP实体(例如带有HttpResponse返回的实体)附加到底层连接,以便能够在没有任何中间缓冲的情况下流式传输数据。在响应内容完全消耗之前关闭HttpResponse会导致基础连接重置。