24

是否有Android會話管理的特定庫?我需要在正常的Android應用程序中管理我的會話。不在WebView。我可以從我的發佈方法中設置會話。但是當我發送另一個會話丟失的請求時。有人可以幫我解決這個問題嗎?Android會話管理

DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("My url"); 

HttpResponse response = httpClient.execute(httppost); 
List<Cookie> cookies = httpClient.getCookieStore().getCookies(); 

if (cookies.isEmpty()) { 
    System.out.println("None"); 
} else { 
    for (int i = 0; i < cookies.size(); i++) { 
     System.out.println("- " + cookies.get(i).toString()); 
    } 
} 

當我試圖訪問同一主機會話丟失:

HttpGet httpGet = new HttpGet("my url 2"); 
HttpResponse response = httpClient.execute(httpGet); 

我得到的登錄頁面響應主體。

回答

38

這與Android無關。它與Apache HttpClient(即用於HTTP訪問的庫)有關。

會話cookie存儲在您的DefaultHttpClient對象中。爲每個請求創建一個新的DefaultHttpClient,而不是爲每個請求創建一個新的DefaultHttpClient,而是堅持並重用它,並保持會話cookie。

您可以閱讀關於Apache HttpClient here並閱讀關於HttpClient here中的cookie管理。

+0

非常感謝你..我會試試這種方式 – nala4ever 2010-11-21 05:42:19

+0

感謝CommonsWare,它真的解決了我的問題。非常感謝.. :) – 2011-05-11 09:47:41

+2

這個鏈接給和想法如何實現這個http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html – Sam 2011-10-05 17:57:47

4

這是我使用的職位。我可以使用此方法使用新的httpClients,其中phpsessid是使用上面的代碼從登錄腳本中提取的PHP會話ID。

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

nameValuePairs.add(new BasicNameValuePair("PHPSESSID",phpsessid)); 
+0

感謝您的信息吉姆 – nala4ever 2010-11-21 05:41:19

3

通常,在Java HttpURLConnection中,您可以通過這種方式設置/獲取cookie(這裏是整個連接過程)。下面的代碼在我的ConnectingThread的run()中,所有連接活動類都從中繼承。全部共享與所有請求一起發送的通用靜態sCookie字符串。因此,你可以保持一個共同的狀態就像被記錄的開/關:

 HttpURLConnection conn = (HttpURLConnection) url.openConnection();    

     //set cookie. sCookie is my static cookie string 
     if(sCookie!=null && sCookie.length()>0){ 
      conn.setRequestProperty("Cookie", sCookie);     
     } 

     // Send data 
     OutputStream os = conn.getOutputStream(); 
     os.write(mData.getBytes()); 
     os.flush(); 
     os.close(); 

     // Get the response! 
     int httpResponseCode = conn.getResponseCode();   
     if (httpResponseCode != HttpURLConnection.HTTP_OK){ 
      throw new Exception("HTTP response code: "+httpResponseCode); 
     } 

     // Get the data and pass them to the XML parser 
     InputStream inputStream = conn.getInputStream();     
     Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);     
     inputStream.close(); 

     //Get the cookie 
     String cookie = conn.getHeaderField("set-cookie"); 
     if(cookie!=null && cookie.length()>0){ 
      sCookie = cookie;    
     } 

     /* many cookies handling:     
     String responseHeaderName = null; 
     for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) { 
      if (responseHeaderName.equals("Set-Cookie")) {     
      String cookie = conn.getHeaderField(i); 
      } 
     }*/     

     conn.disconnect();     
0

完全透明的方式來保持會話活躍(用戶登錄,或其他)的Android應用。 它使用Singleton中的apache DefaultHttpClient和一個HttpRequest/Response攔截器。

SessionKeeper類只是檢查其中一個標頭是否爲Set-Cookie,如果是,它只會記住它。 SessionAdder只是將會話ID添加到請求中(如果不爲空)。 這樣,你的整個認證過程是完全透明的。

public class HTTPClients { 

    private static DefaultHttpClient _defaultClient; 
    private static String session_id; 
    private static HTTPClients _me; 
    private HTTPClients() { 

    } 
    public static DefaultHttpClient getDefaultHttpClient(){ 
     if (_defaultClient == null) { 
      _defaultClient = new DefaultHttpClient(); 
      _me = new HTTPClients(); 
      _defaultClient.addResponseInterceptor(_me.new SessionKeeper()); 
      _defaultClient.addRequestInterceptor(_me.new SessionAdder()); 
     } 
     return _defaultClient; 
    } 

    private class SessionAdder implements HttpRequestInterceptor { 

     @Override 
     public void process(HttpRequest request, HttpContext context) 
       throws HttpException, IOException { 
      if (session_id != null) { 
       request.setHeader("Cookie", session_id); 
      } 
     } 

    } 

    private class SessionKeeper implements HttpResponseInterceptor { 

     @Override 
     public void process(HttpResponse response, HttpContext context) 
       throws HttpException, IOException { 
      Header[] headers = response.getHeaders("Set-Cookie"); 
      if (headers != null && headers.length == 1){ 
       session_id = headers[0].getValue(); 
      } 
     } 

    } 
}