Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android session management

Tags:

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.

like image 434
nala4ever Avatar asked Nov 19 '10 12:11

nala4ever


People also ask

What is Session Management Android?

A class that manages Session instances. The application can attach a SessionManagerListener to be notified of session events. SessionManager works with Android MediaRouter on managing session lifecycle. The current session always uses the current selected route (which corresponds to MediaRouter.

How do I keep logged in on Android?

When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out. Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.

What is Android shared preference?

A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.


2 Answers

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.

like image 67
CommonsWare Avatar answered Oct 20 '22 12:10

CommonsWare


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)); 
like image 24
Jim Avatar answered Oct 20 '22 12:10

Jim