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
会在关闭entity
和response
后重置httpClient
?
答案 0 :(得分:4)
我的问题是,为什么httpclient会在关闭响应和httpClient后重置实体?
流式HTTP实体(例如带有HttpResponse
返回的实体)附加到底层连接,以便能够在没有任何中间缓冲的情况下流式传输数据。在响应内容完全消耗之前关闭HttpResponse
会导致基础连接重置。