How to Handle the Session in Apache HttpClient 4.1
47,423
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);
// ...
Author by
special0ne
Updated on July 09, 2022Comments
-
special0ne almost 2 years
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?
-
Ankur Loriya about 12 yearsin case of session expired what happen ?
-
Siddhartha almost 6 years@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.