How to maintain server login throughout the android native application?
android, authentication, cookies, json, session
Solution
finally Its working for me :)
instead of using new DefaultHttpClient all the time , I have made it static & used just once.
static DefaultHttpClient client = new DefaultHttpClient();
Problem
Let me describe my application , I am fetching data from the website JSON url (Drupal website) , data is in JSON format. In my application login functionality works perfectly . & user is validated on the server. I am also fetching other data(JSON url) from the server & displaying in my android application. Now, the problem is that I can’t access JSON data of pages , where login is required , because my login is not maintaining throughout the android application. I have searched on stackoverflow & google I got these links & tried but don't know how to use them in my code: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html Android session management Http cookie store in Android Here is the Empty JSON that is from drupal site without login. ``` { "nodes": [] } ``` Here is the JSON from drupal site- after login(http://www.mywebsite.com/user/login) & reload the page http://www.mywebsite.com/myaccount-page on the site - in computer webbrowser . means computer web browser automatically maintains the login session. ``` { "nodes": [ { "node": { "Uid": "51", "Username": "anand", "Name": "anand", "Address": "\n\tAt- vadodara Nr. Kareli Baugh", "Date of Birth": "1998-08-20", "Occupation": "student", "Member Since": "36 weeks 6 days" } } ] } ``` But in android application it does not do this automatically. So I want to maintain this session in Android so that I can login in android application , after login redirect to another page-activity & get JSON data there. Here is my code: LoginActivity.java ``` public void onClick(View v) { String uName = editUser.getText().toString(); String Password = editPass.getText().toString(); if(uName.equals("") | Password.equals("")) { Toast.makeText(getApplicationContext(), "Enter the Username and Password",Toast.LENGTH_SHORT).show(); } else{ String strResponse = util.makeWebCall(loginURL,uName,Password); System.out.println("=========> Response from login page=> " + strResponse); try{ if (strResponse.substring(KEY_SUCCESS) != null) { txterror.setText(""); Intent inlogin = new Intent(LoginActivity.this, post_myprofile.class); inlogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(inlogin); //finish(); } else { txterror.setText("Username and Password Not valid !!!"); } } catch (Exception e) { // TODO: handle exception } } } }); btngotoregister.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(getApplicationContext(), RegisterActivity.class); // intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); } }); } } ``` makeWebCall method in util.java util.java ``` public static String makeWebCall(String url, String uname,String pass) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username",uname)); params.add(new BasicNameValuePair("password",pass)); UrlEncodedFormEntity formEntity = null; try { formEntity = new UrlEncodedFormEntity(params); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } post.setEntity(formEntity); try { //post.setEntity(new StringEntity(requestString)); HttpResponse response = client.execute(post); System.out.println("=========> Responsehello => "+response); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); return iStream_to_String(is); } else { return "Hello This is status ==> :"+String.valueOf(statusCode); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } ``` Now with this code login is successful & I got the JSON response from the server with detail. & page-activity redirects to 2nd page for user profile. On 2nd page I am not getting the userprofile JSON data-As mentioned above , I am getting Blank JSON because session is not maintained. Here is the code of the 2nd page-activity. post_myprofile.java ``` protected Void doInBackground(Void... params) { // TODO Auto-generated method stub String url = "http://www.cheerfoolz.com/myaccount-page"; String strResponse = util.makeWebCall(url); try { JSONObject objResponse = new JSONObject(strResponse); JSONArray jsonnodes = objResponse .getJSONArray(API.cheerfoolz_myprofile.NODES); ``` makewebcall method for profile in util.java util.java ``` public static String makeWebCall(String url) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpRequest = new HttpGet(url); // HttpPost post = new HttpPost(url); try { HttpResponse httpResponse = client.execute(httpRequest); final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { /* Log.i(getClass().getSimpleName(), "Error => " + statusCode + " => for URL " + url);*/ return null; } HttpEntity entity = httpResponse.getEntity(); InputStream is = entity.getContent(); return iStream_to_String(is); } catch (IOException e) { httpRequest.abort(); // Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e); } return null; } public static String iStream_to_String(InputStream is1) { BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096); String line; StringBuilder sb = new StringBuilder(); try { while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String contentOfMyInputStream = sb.toString(); return contentOfMyInputStream; } } ``` I am getting blank JSON here in this page - that I have mentioned above. so how to maintain session in this user profile activity & get the data? Thanks For listening.