2011-05-28 38 views
5

從Android訪問servlet時,我無法保持會話。我只是將參數和URL一起傳遞給從數據庫收集數據並將其存儲在會話中的servlet,但是我無法在隨後的請求中檢索它。從Android訪問servlet時維護HTTP會話

當我關閉servlet中的PrintWriter時會話過期嗎?

回答

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