31
votes

I'm writing a java app that can login and shop around on the website. I'm having an issue where my HttpClient is hanging when I try to execute a second HttpResponse/Post. It was working fine before, not sure why it started hanging up. I don't get any errors, it just sits there and gets stuck. The only change I made that may be possibily causing this hang up is that I'm using HttpGet to retrieve tokens so I can login to the website.

Here's how I'm setting up the httpClient

private static BasicCookieStore cookieStore = new BasicCookieStore();
private static HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

The rest is just a standard httpget & httppost, then httpclient.execute();

The first sequence is my program queries the website and retrieves the token, then I send a POST with the token to sign in. After that my program queries a website again to get product information, then adds to the cart. But it hangs at the second POST.

Could I be missing a flush somewhere? I was reading somewhere that this way of HttpClient closes itself. And the DefaultHttpClient has been deprecated.

2
Please show a short but complete program demonstrating the problem. - Jon Skeet
What do you mean by "hangs"? is there an exception? what's the message? - Maurice Perry
I suspect the problem is in your "standard" usage of the class ... you're probably not cleaning up something you should be ... you should provide a short example that demonstrates the problem. ETA: You even ask if you're missing a flush somewhere -- how on earth would we know without code? - dcsohl

2 Answers

45
votes

In the tutorial posted it below, they did not mention I should use post.releaseConnection(); It caused my code to hangup, so I addeded the releaseConnection() function after every POST/GET. I hope that is the proper way to clean the code up.

1
votes

Option 1: Reset the Request

releaseConnection() or reset() will "reset internal state of the request making it reusable":

HttpGet request = new HttpGet("https://httpbin.org/get");
try (CloseableHttpClient client = HttpClients.createDefault()) {   
    CloseableHttpResponse response = client.execute(request)  
    // do something with response
} finally {
    request.releaseConnection()
}

Option 2: Close the Response

Call response.close() once we are finished handling the response:

HttpGet request = new HttpGet("https://httpbin.org/get");
try (CloseableHttpClient client = HttpClients.createDefault()) {
    try {   
    CloseableHttpResponse response = client.execute(request)  
    // do something with response
    } finally {
        response.close()
    }
}

We can tidy this up by adding the response to the try-with-resources statement:

HttpGet request = new HttpGet("https://httpbin.org/get");
try (CloseableHttpClient client = HttpClients.createDefault();
     CloseableHttpResponse response = client.execute(request)) {
    // do something with response
}