HttpClient在执行两次后停止在循环中执行相同的HttpGet方法

HttpClient stop executing the same HttpGet method in a loop after executing twice

这是我的主要方法:

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();
        }
    }
}

HttpClient 执行2次后停止执行同一个HttpGet。虽然,我在循环中实例化了一个新的 HttpClient,但它不会停止。我想知道是否有某种策略阻止 HttpClient 执行相同的 HttpGet 方法超过 2 次? 谁能帮帮我,感激不尽!

客户端正在使用连接池访问 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();
        }
    }
}