java – Android session management-ThrowExceptions

Exception or error:

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.

How to solve:

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.

###

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

###

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

###

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

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *