Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient hangs when doing a second request

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.

like image 481
user3630509 Avatar asked Oct 26 '15 16:10

user3630509


2 Answers

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.

like image 161
user3630509 Avatar answered Nov 19 '22 18:11

user3630509


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
}
like image 3
rusheb Avatar answered Nov 19 '22 18:11

rusheb