Session maintenance in android (application remains authenticated on server side)

I am creating an android login application in which I find the url (with username and password) to this part, it works fine, but after that whenever I click the url (after user authentication), it’s nothing does not return (for example, an error message, for example, please log in). However, it works great in a very similar iphone application and in the browser.

I found somewhere that this is a phpSessionId error (i.e. the session was destroyed for further request), and if we want our Android application to remain authenticated on the server side, we need to get this identifier after the first connection, and then send it in the headers of all our subsequent requests.

But the problem is that I can not get sessionId from the header of the first connection and send it with a further request along with the header.

Please give me some codes or links to complete the task properly. Thank you

+30
android session session-state
May 11 '11 at 7:40 a.m.
source share
5 answers

Finally, I solved the session handling issue in Android . Android can not handle the session itself (which can be a simple browser), so we must handle it explicitly. I changed the code for the http connection a bit. Created an instance of DefaultHttpClient in the first step when the connection is established.

public static DefaultHttpClient httpClient; 

For the first time, 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 subsequent connections, I used the same httpClient, for example, in the following action:

 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 helps you all solve the session issue in Android .

+46
May 19 '11 at 6:46
source share

It’s best to put the whole function that your server does in a unique class that will be called up by the tasks you want to connect to. I call this class WebServiceManager. This class has the same method as the server.

How do you need a unique session:

 private static WebServiceManager wsm = null; public static WebServiceManager getInstance() { if (wsm == null) { wsm = new WebServiceManager(); } return wsm; } private final HttpClient httpClient; private WebServiceManager() { httpClient=new DefaultHttpClient(); } 

and then you call the method of your webServiceManager instance to always use the same session. :)

+2
Apr 22 '14 at 13:35
source share

My problem was that I first logged in and saved the returned session to userpreferences. After that, the post call to set up the record said

"Error, unable to authenticate user"

So, I added post.setHeader("oAuth-Token", UserPreferences.ACCESS_TOKEN); it all looks like this.

 HttpPost post=new HttpPost(URL ); post.setHeader("oAuth-Token", UserPreferences.ACCESS_TOKEN); 

. and he solved the problem.

0
Nov 25 '13 at 7:45
source share

I wrote a post about this a while ago on coderwall. It uses the HttpRequestInterceptor and HttpResponseInterceptor classes, which are ideal for this kind of scenario.

Here is an example:

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

}

0
May 2, '15 at 15:18
source share

Here is another implementation using the Volley library ... a very useful hint from https://stackoverflow.com/a/16737/ ...

  CustomRequest jsonObjReq = new CustomRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog } }); 

Custom Request Class

 import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class CustomRequest extends JsonObjectRequest { private String session_id = ""; public CustomRequest(int method, String url, JSONObject jsonRequest, Response.Listener listener, Response.ErrorListener errorListener) { super(method, url, jsonRequest, listener, errorListener); } public CustomRequest(int method, String url, JSONObject jsonRequest, String session_id, Response.Listener listener, Response.ErrorListener errorListener) { super(method, url, jsonRequest, listener, errorListener); this.session_id = session_id; } @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap(); Log.d(TAG, " -> session_id = " + session_id); if(!(session_id.equals(""))) { headers.put("Cookie", this.session_id); } return headers; } } 

A simple way to implement volleyball using a singleton pattern http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/

Remember to initialize mRequestQueue in onCreate () to avoid unexpected null pointer exception

 @Override public void onCreate() { super.onCreate(); // initialize the singleton sInstance = this; mRequestQueue = Volley.newRequestQueue(this); } 

Hope this help too ...! :)

0
Jul 20 '16 at 5:48
source share



All Articles