Last Updated: September 09, 2019
·
18.26K
· Lior Zimmerman

A nice way to maintain server session id on Android.

This a nice, 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();
            }
        }

    }
}