Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle the Session in Apache HttpClient 4.1

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?

like image 896
special0ne Avatar asked Jun 07 '11 23:06

special0ne


People also ask

Do we need to close HttpClient connection?

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.


1 Answers

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); // ... 
like image 82
BalusC Avatar answered Sep 26 '22 16:09

BalusC