这是我的主要方法:
public static void main(String[] args) {
BasicCookieStore cookieStore = null;
HttpResponse httpResponse = null;
HttpClient httpClient = HttpClients.createDefault();
while (true) {
HttpUriRequest request = new HttpGet("http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html");
try {
httpResponse = httpClient.execute(request);
System.out.println(httpResponse.getStatusLine().getStatusCode());
} catch (Exception e) {
System.out.println(httpResponse.getStatusLine().getStatusCode());
e.printStackTrace();
}
}
}
执行2次后,HttpClient停止执行相同的HttpGet。虽然,我在循环中实例化一个新的HttpClient,但它不会停止。如果有什么策略阻止HttpClient执行相同的HttpGet方法超过2次,我会徘徊? 谁能帮助我,我将非常感激!
答案 0 :(得分:7)
客户端正在使用连接池来访问Web服务器。见HttpClientBuilder#build()。创建默认的httpclient并且未指定任何内容时,它会创建一个大小为2的池。因此,在使用2之后,它会无限期地等待尝试从池中获取第三个连接。
您必须阅读响应或关闭连接才能重新使用客户端对象。
请参阅更新的代码示例:
public static void main(String[] args) {
BasicCookieStore cookieStore = null;
HttpResponse httpResponse = null;
HttpClient httpClient = HttpClients.createDefault();
while (true) {
HttpUriRequest request = new HttpGet("http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html");
try {
httpResponse = httpClient.execute(request);
httpResponse.getEntity().getContent().close();
System.out.println(httpResponse.getStatusLine().getStatusCode());
} catch (Exception e) {
System.out.println(httpResponse.getStatusLine().getStatusCode());
e.printStackTrace();
}
}
}