Maintaining HTTP session when accessing a servlet from Android
I am not able to maintain session when I access a servlet from An开发者_Python百科droid. 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?
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
精彩评论