Maintaining session in android ( application stay authenticated on the server side)

Finally I solved the issue of session handling in Android.
Android cant handle the session itself(which a simple browser can) so we have to handle it explicitly.
I changed the code for http connection a bit.
Created an instance of DefaultHttpClient in the first Activity when connection established.

public static DefaultHttpClient httpClient;

For the first time connection,I did the following:

URL url=new URL(urlToHit);
LoginScreen.httpClient = new DefaultHttpClient(); //LoginScreen is the name of the current Activity

HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost); 

xr.parse(new InputSource(url.openStream())); //SAX parsing

Now for all further connections I used the same httpClient
For example in the next activity:

URL url=new URL(urlToHit);

HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost); 

// Log.v("response code",""+response.getStatusLine().getStatusCode());

// Get hold of the response entity
HttpEntity entity = response.getEntity();

InputStream instream = null;

if (entity != null) {
    instream = entity.getContent();
}
xr.parse(new InputSource(instream)); //SAX parsing

Hope this will help you all too to solve session issue in Android.

Leave a Comment