Maintaining HTTP session when accessing servlet from Android

I cannot maintain a session when I access servlets with Android. I just pass the parameters along with the URL of the servlet that collects the data from the database and stores it in the session, but I can not get it on subsequent requests.

Does the session end when I close PrintWriterthe servlet?

+5
source share
1 answer

This is a client side issue. HTTP session supported by cookie. The client must ensure that it correctly sends the cookie to subsequent requests in accordance with the HTTP specification. The HttpClient API offers a class CookieStorethat needs to be set to HttpContext, which you, in turn, need to pass to each call HttpClient#execute().

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 work, read this answer: How do servlets work? Create, Sessions, Shared Variables, and Multithreading

+4
source

All Articles