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.
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.
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()
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With