How to Handle the Session in Apache HttpClient 4.1
Asked Answered
M

1

43

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?

Mulvey answered 7/6, 2011 at 23:3 Comment(0)
T
73

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);
// ...
Thyrotoxicosis answered 8/6, 2011 at 2:44 Comment(2)
in case of session expired what happen ?Silvester
@Ankur, usually the server will notice that the session is expired and redirect you to a login page. If your request was read-only, it will redirect you to the page after successful auth, but if it was mutative you will have to do it again.Tereus

© 2022 - 2024 — McMap. All rights reserved.