42

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?

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
special0ne
  • 6,063
  • 17
  • 67
  • 107

1 Answers1

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);
// ...
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 17
    in case of session expired what happen ? – Ankur Loriya Mar 28 '12 at 06:42
  • 1
    @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. – Siddhartha Jun 07 '18 at 18:53