【问题标题】:Android session management安卓会话管理
【发布时间】:2011-05-12 14:44:24
【问题描述】:

是否有用于 Android 会话管理的特定库?我需要在普通的 Android 应用程序中管理我的会话。不在WebView。我可以从我的 post 方法设置会话。但是当我发送另一个请求时,会话丢失了。有人可以帮我解决这个问题吗?

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

我得到登录页面响应正文。

【问题讨论】:

    标签: java android session session-cookies apache-commons-httpclient


    【解决方案1】:

    这与安卓无关。它与您用于 HTTP 访问的库 Apache HttpClient 有关。

    会话 cookie 存储在您的 DefaultHttpClient 对象中。不要为每个请求创建一个新的DefaultHttpClient,而是保留它并重复使用它,这样您的会话 cookie 就会得到维护。

    您可以阅读 Apache HttpClient here 并阅读 HttpClient here 中的 cookie 管理。

    【讨论】:

    • 非常感谢..我会这样尝试
    • 感谢 CommonsWare,它确实解决了我的问题。非常感谢..:)
    • 这个链接给出了如何实现这个foo.jasonhudgins.com/2009/08/…的想法
    【解决方案2】:

    这是我用来发帖的。我可以通过这种方法使用新的httpClients,其中phpsessid 是使用上面的代码从登录脚本中提取的PHP 会话ID。

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    
    nameValuePairs.add(new BasicNameValuePair("PHPSESSID",phpsessid));
    

    【讨论】:

      【解决方案3】:

      一般来说,在Java HttpURLConnection 中你可以通过这种方式设置/获取cookie(这里是整个连接过程)。下面的代码在我的 ConnectingThread 的 run() 中,所有连接活动类都从该 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();                
      

      【讨论】:

        【解决方案4】:

        在 Android 应用中保持会话活动(用户登录或其他)的完全透明的方式。 它在 Singleton 和 HttpRequest/Response 拦截器中使用 apache DefaultHttpClient。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-07
          • 2012-08-18
          • 2012-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多