gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:43:06 27 4
gpt4 key购买 nike

  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会在关闭responsehttpClient后重置entity

最佳答案

My question is, why httpclient will reset entity after closing response and httpClient?

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

关于java - HttpEntity 在关闭后重置并抛出 java.net.SocketException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29228703/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com