3

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!

zhongwei
  • 325
  • 1
  • 5
  • 15

1 Answers1

11

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();
        }
    }
}
stalet
  • 1,345
  • 16
  • 24