HttpClient执行两次后,在循环中停止执行相同的HttpGet方法 [英] HttpClient stop executing the same HttpGet method in a loop after executing twice

查看:224
本文介绍了HttpClient执行两次后,在循环中停止执行相同的HttpGet方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的主要方法:

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之后,停止执行相同的HttpGet.同时,我在循环中实例化了一个新的HttpClient,它不会停止.我是否在寻找某种策略来阻止HttpClient执行同一个HttpGet方法两次以上? 谁能帮助我,我将不胜感激!

After executing 2 times the HttpClient stop executing the same HttpGet. While, I instantiate a new HttpClient in the loop, it won't stop. I wander if there is something strategy preventing the HttpClient from executing the same HttpGet method more than 2 times? Who can help me, I will be very grateful!

推荐答案

客户端正在使用连接池访问Web服务器.参见

The client is using a pool of connection to reach the web server. See HttpClientBuilder#build(). When creating a default httpclient and nothing is specified it creates a pool with size of 2. So after 2 is used, it waits indefinitely trying to get the third connection from the pool.

您必须阅读响应或关闭连接,才能重新使用客户端对象.

You must read the response or close the connection, in order to re-use the client object.

查看更新的代码示例:

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

这篇关于HttpClient执行两次后,在循环中停止执行相同的HttpGet方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆