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

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

4

4 回答 4

39

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

会话 cookie 存储在您的DefaultHttpClient对象中。与其为每个请求创建一个新DefaultHttpClient请求,不如保留并重用它,您的会话 cookie 将被维护。

您可以在此处阅读有关 Apache HttpClient的信息,并在此处阅读有关 HttpClient 中的 cookie 管理的信息

于 2010-11-19T12:37:11.253 回答
4

这是我用于帖子的。我可以httpClients在这种方法中使用 new ,使用上面的代码从登录脚本中提取phpsessid的会话 id 在哪里。PHP

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

nameValuePairs.add(new BasicNameValuePair("PHPSESSID",phpsessid));
于 2010-11-19T15:46:47.727 回答
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();                
于 2011-02-24T09:44:43.947 回答
0

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

    }
}
于 2017-04-06T06:24:23.637 回答