Android 会话管理

发布于 2024-10-03 04:30:44 字数 742 浏览 3 评论 0原文

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

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

Is there a specific library for Android session management? I need to manage my sessions in a normal Android app. not in WebView. I can set the session from my post method. But when I send another request that session is lost. Can someone help me with this matter?

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

When I try to access the same host that session is lost:

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

I get the login page response body.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

醉梦枕江山 2024-10-10 04:30:44

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

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

您可以在此处阅读有关 Apache HttpClient 的信息,并阅读有关 HttpClient 中 cookie 管理的信息 < a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html" rel="noreferrer">此处。

This has nothing to do with Android. It has everything to do with Apache HttpClient, the library you are using for HTTP access.

Session cookies are stored in your DefaultHttpClient object. Instead of creating a new DefaultHttpClient for every request, hold onto it and reuse it, and your session cookies will be maintained.

You can read about Apache HttpClient here and read about cookie management in HttpClient here.

拍不死你 2024-10-10 04:30:44

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

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

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

This is what I use for posts. I can use new httpClients with this method where phpsessid is the PHP session id extracted from the login script using the code you have above.

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

nameValuePairs.add(new BasicNameValuePair("PHPSESSID",phpsessid));
温柔一刀 2024-10-10 04:30:44

一般来说,在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();                

Generally, in Java HttpURLConnection you can set / get a cookie this way (here is the whole connection process). The code below is in my ConnectingThread's run(), from which all the connecting activity classes inherit. All share common static sCookie string which is sent with all the requests. Therefore you can maintain a common state like being logged on / off:

        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();                
猫七 2024-10-10 04:30:44

在 Android 应用程序中保持会话活动(用户登录或其他)的完全透明的方式。
它在 Singleton 和 HttpRequest/Response Interceptors 中使用 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();
            }
        }

    }
}

Totally transparent way to keep a session active (user logged in , or whatever) in Android apps.
It uses the apache DefaultHttpClient inside a Singleton and a HttpRequest/Response Interceptors.

The SessionKeeper class simply checks whether one of the headers is Set-Cookie, and if it does, it simply remembers it.
The SessionAdder simply adds the session id to the request (if not null).
This way, you the whole authentication process is totally transparent.

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

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文