I am using the HttpClient 4.1.1 to test my server's REST API.
I can manage to login seem to work fine but when I try to do anything else I am failing.
Most likely I have a problem setting the cookie in the next request.
Here is my code currently:
HttpGet httpGet = new HttpGet(<my server login URL>); httpResponse = httpClient.execute(httpGet) sessionID = httpResponse.getFirstHeader("Set-Cookie").getValue(); httpGet.addHeader("Cookie", sessionID); httpClient.execute(httpGet);
Is there a better way to manage the session/cookies setting in the HttpClient package?
You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.
The correct way is to prepare a CookieStore
which you need to set in the HttpContext
which you in turn pass on every HttpClient#execute()
call.
HttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); // ... HttpResponse response1 = httpClient.execute(method1, httpContext); // ... HttpResponse response2 = httpClient.execute(method2, httpContext); // ...
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