从Android访问servlet时维护HTTP会话

时间:2011-05-28 05:27:27

标签: java android servlets

当我从Android访问servlet时,我无法维护会话。我只是将参数和URL一起传递给servlet,servlet从数据库中收集数据并将其存储在会话中,但我无法在后续请求中检索它。

当我关闭servlet中的PrintWriter时,会话是否会过期?

1 个答案:

答案 0 :(得分:4)

这是客户端的问题。 HTTP会话由cookie维护。客户端需要确保根据HTTP规范正确地将cookie发送回后续请求。 HttpClient API为此提供CookieStore类,您需要在HttpContext中设置该类,而您需要在每次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);
// ...

要详细了解会话的工作原理,请阅读以下答案:How do servlets work? Instantiation, sessions, shared variables and multithreading