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

3

这是我的 Main 方法:

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次?谁能帮助我,我将非常感激!


尝试消耗响应实体。 - kupsef
问题完美解决!谢谢! - zhongwei
1个回答

11
客户端使用连接池来连接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();
        }
    }
}

我明白了。非常感谢!StackOverflow对我来说是一个不错的地方。 - zhongwei
@Zavael,我也想知道这是为什么。它确实会执行两次。 - zhongwei
2
客户端使用连接池来访问Web服务器。请参见HttpClientBuilder#build()。当创建默认的httpclient并且没有指定任何内容时,它会创建一个大小为2的池。因此,在使用2个连接后,它会无限期地等待尝试从池中获取第三个连接。 - stalet
哇!你们都太厉害了!谢谢! - zhongwei
1
@Zavael:已更新答案。 - stalet
显示剩余3条评论

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