Last Updated: March 08, 2016
· zman
2125 58556031154 1554 n

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( SessionKeeper());
            _defaultClient.addRequestInterceptor( SessionAdder());
        return _defaultClient;

    private class SessionAdder implements HttpRequestInterceptor {

        public void process(HttpRequest request, HttpContext context)
                throws HttpException, IOException {
            if ( session_id != null ) {
                request.setHeader("Cookie", session_id);


    private class SessionKeeper implements HttpResponseInterceptor {

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