I was able log in through my android app to http://yearbook08.com/ using this code:
String URL="http://yearbook08.com/login.php";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now when I move to another activity I want to retrieve http://yearbook08.com/wall.php but the web server does not recognize my last login and asks me to login again.
Is there a way that I can stay logged in after once logging in? Kindly help !
Your code does not take into account session management. This happening as after a successful login no cookies are set, so if you send another request the initial authentication is lost and server takes it to be a fresh request.
I would suggest you use Apache httpcomponents library 4.x (httpclient in particular)
Create a httpcontext and attach a cookie store as
Make use the same localContext in the subsequent requests. Also note cookiestore and httpcontext should be declared as static or global variables as their scope must exist wherever you carry the httprequest. You don’t have to set cookies on your own, it is automatically done!
And do read about HttpComponents 4.x http://hc.apache.org/httpcomponents-client-ga/index.html
Update 1:
Make sure it is v4 and v3. basicCookiestore has only been present since v4. It is clear now that you are using v3 which does not know about basiccookiestore object. Add the v4 library to your project. It will solve your problem
Update 2
If you try to retrieve http://yearbook08.com/wall.php from the 2nd activity this problem will arise as the 2nd activity won’t have httpcontext,httpclient or the Cookiestore object in it. So it will send a fresh request.
1st approach
So you should try to fetch the contents you need in the first activity itself and then pass on the fetched data to the 2nd activity. This way you’ll have session maintained.
2nd soln
If you are not satisfied with this you can check this out http://www.jameselsey.co.uk/blogs/techblog/android-implementing-global-state-share-data-between-activities-and-across-your-application/ Share httpcontext, cookiestore and httpclient across the activities to accomplish the task.