Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining HTTP session when accessing a servlet from Android

I am not able to maintain session when I access a servlet from Android. I just pass the parametres along with the URL to the servlet which gathers data from database and stores it in the session, but I am not able to retrieve it on subsequent requests.

Does the session get expired when I close the PrintWriter in the servlet?

like image 804
MMM Avatar asked Oct 11 '22 22:10

MMM


1 Answers

This is a problem in the client side. The HTTP session is maintained by a cookie. The client needs to ensure that it properly sends the cookie back on the subsequent requests as per the HTTP spec. The HttpClient API offers the CookieStore class for this which you need to set in the HttpContext which you in turn need to pass on every HttpClient#execute() call.

HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// ...

HttpResponse response1 = httpClient.execute(yourMethod1, httpContext);
// ...

HttpResponse response2 = httpClient.execute(yourMethod2, httpContext);
// ...

To learn more about how sessions works, read this answer: How do servlets work? Instantiation, sessions, shared variables and multithreading

like image 65
BalusC Avatar answered Oct 14 '22 01:10

BalusC