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

4
  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
  }

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

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


谢谢您的提问。我曾经遇到过完全相同的错误,这个帮助了我解决了它。 - DXM
1个回答

4
我的问题是,为什么在关闭响应和httpClient之后,httpclient会重置实体?流式传输的HTTP实体(例如那些与HttpResponse一起返回的实体)附加到底层连接上,以便能够在没有任何中间缓冲的情况下流式传输数据。在完全消耗响应内容之前关闭HttpResponse会导致底层连接被重置。

@Sayakiss有没有优雅的方式来解决这个问题? - Magnus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接