Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here is my Main Method:

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

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!

like image 482
zhongwei Avatar asked Jan 25 '26 10:01

zhongwei


1 Answers

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.

See updated code sample:

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();
        }
    }
}
like image 115
stalet Avatar answered Jan 27 '26 23:01

stalet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!