Reputation:
Checked many similar topics but still couldn't quite find the right answer.
I'm trying to make an Android application where users log in and connect to the server to retrieve some data. Sadly I cannot get past the part where I need the app to maintain session between the app and the server. Just not sure how to do it correctly.
As far as I have read and understood, the process is like this - user clicks the login button and the request to the server is sent. Then the response is received and it contains the cookie with the session id. I save the session id in SharedPreferences for later use. When the next activity is loaded, I retrieve this id from SharedPreferences, add it to the next HTTP request, so the correct session is maintained. Correct me if I'm wrong.
The problem is with adding session id to HTTP requests. What should be changed in the code below in order to maintain session between the app and server even when the application gets destroyed and then opened later again? How should the cookie be correctly added to the request? It doesn't seem I'm doing it right...
My code is as follows:
public class LoginScreen extends Activity {
DefaultHttpClient httpclient = new DefaultHttpClient();
SharedPreferences prefs;
Editor editor;
Button login_button;
String session_cookie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
prefs = this.getSharedPreferences("filetitlehere", Context.MODE_PRIVATE);
editor = prefs.edit();
session_cookie = prefs.getString("sessionid", "not saved");
if (session_cookie != "not saved") {
// intent to another activity
} else {
login_button = (Button)findViewById(R.id.button_login);
login_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new Login().execute("http://mywebpage.com/login");
} else {
// error
}
}
});
}
}
private class Login extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url) {
try {
return auth(url[0]);
} catch (IOException e) {
return "an error";
}
}
protected void onPostExecute(String result) {
JSONObject jsonobj;
Integer user_auth = 0;
try {
jsonobj = new JSONObject(result);
user_auth = jsonobj.getInt("auth");
} catch (JSONException e) {
// error
}
if (user_auth == 0) { // in case user not logged in
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
for (Cookie ck : cookies) {
if (ck.getName() == "PHPSESSID") {
// saved in SharedPreferences for later use
prefs.edit().putString("sessionid", ck.getValue().toString()).commit();
}
}
} else {
// user already logged in
Intent intent = new Intent(getApplicationContext(), HomeScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
private String auth(String myurl) throws IOException {
try {
HttpPost httppost = new HttpPost(myurl);
if (session_cookie == "not saved") {
// without adding cookie, cause cookie not saved in SharedPreferences
HttpResponse response = httpclient.execute(httppost);
} else {
// adding sessionid from SharedPreferences
BasicCookieStore cstore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("PHPSESSID",session_cookie);
cstore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cstore);
HttpResponse response = httpclient.execute(httppost, localContext);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder resp = new StringBuilder();
String line = null;
while((line = bufferedReader.readLine()) != null){
resp.append(line);
}
return resp.toString();
} catch (UnsupportedEncodingException e) {
// error
} catch (ClientProtocolException e) {
// error
} catch (IOException e) {
// error
}
}
}
Some other questions:
Thank you in advance!
Upvotes: 2
Views: 1432
Reputation:
A long time since I asked this question. Instead of writing session management myself, I switched to using loopj's client - http://loopj.com/android-async-http.
Solved everything and works brilliantly!
Upvotes: 1