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(); 
      } 
     } 

    } 
}