2012-05-09 23 views
5

Để tôi mô tả ứng dụng của mình, Tôi đang tìm nạp dữ liệu từ url của trang web JSON (trang web Drupal), dữ liệu ở định dạng JSON. Trong chức năng đăng nhập ứng dụng của tôi hoạt động hoàn hảo. & người dùng được xác thực trên máy chủ. Tôi cũng tìm nạp dữ liệu khác (url JSON) từ máy chủ & hiển thị trong ứng dụng Android của tôi. Bây giờ, vấn đề là tôi không thể truy cập dữ liệu JSON của trang, nơi đăng nhập là bắt buộc, vì đăng nhập của tôi không duy trì trong suốt ứng dụng Android.Làm cách nào để duy trì đăng nhập máy chủ trong toàn bộ ứng dụng gốc của Android?

tôi đã tìm kiếm trên stackoverflow & google tôi có những liên kết này & cố gắng nhưng không biết làm thế nào để sử dụng chúng trong mã của tôi: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html

Android session management

Http cookie store in Android

đây là JSON trống là từ trang web drupal mà không cần đăng nhập.

{ 
    "nodes": [] 
} 

Đây là JSON từ drupal trang web- sau khi đăng nhập (http://www.mywebsite.com/user/login) & tải lại trang http://www.mywebsite.com/myaccount-page trên trang web - trong máy tính webbrowser. có nghĩa là trình duyệt web máy tính sẽ tự động duy trì phiên đăng nhập.

{ 
"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" 
     } 
    } 
] 
} 

Nhưng trong ứng dụng android, nó không tự động thực hiện việc này. Vì vậy, tôi muốn duy trì phiên này trong Android để tôi có thể đăng nhập trong ứng dụng Android, sau khi đăng nhập chuyển hướng đến trang hoạt động khác & nhận dữ liệu JSON ở đó. Đây là mã của tôi:

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

     } 
    }); 
} 
} 

phương pháp makeWebCall trong 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; 
} 

Bây giờ với mã này đăng nhập thành công & Tôi nhận được phản hồi JSON từ máy chủ với chi tiết. & chuyển hướng trang hoạt động sang trang thứ 2 cho hồ sơ người dùng. Trên Trang thứ hai Tôi không nhận được dữ liệu JSON của người dùng như đã đề cập ở trên, tôi nhận được JSON trống vì phiên không được duy trì.

Đây là mã của hoạt động trang thứ 2.

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

phương pháp makewebcall cho cấu hình trong 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; 
} 


} 

Tôi nhận JSON trống ở đây trong trang này - mà tôi đã đề cập ở trên. Vậy làm thế nào để duy trì phiên trong hoạt động hồ sơ người dùng này & lấy dữ liệu?

Cảm ơn bạn đã nghe.

Trả lời

3

cuối cùng làm việc của nó đối với tôi :)

thay vì sử dụng mới DefaultHttpClient tất cả các thời gian, tôi đã làm cho nó tĩnh & sử dụng chỉ một lần.

static DefaultHttpClient client = new DefaultHttpClient(); 
+0

Thank you very much .. Đây là giúp đỡ rất nhiều :) – Dave

0
package com.velmurugan.vazbo_new.utility; 
import android.webkit.CookieManager; 
import android.webkit.CookieSyncManager; 
import org.apache.http.Header; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpException; 
import org.apache.http.HttpRequest; 
import org.apache.http.HttpRequestInterceptor; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpResponseInterceptor; 
import org.apache.http.HttpStatus; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.cookie.Cookie; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.protocol.HttpContext; 
import java.io.*; 
import java.util.ArrayList; 
import java.util.List; 
/** 
* Created by [email protected] on 11/1/2015. 
*/ 
public class SessionParser { 
    public SessionParser(){ 
    } 
    public static String makeWebCall(String url,List<NameValuePair> params ) 
    { 
     CommonClass.httpClient = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(url); 
     UrlEncodedFormEntity formEntity = null; 
     try { 
      formEntity = new UrlEncodedFormEntity(params); 
     } catch (UnsupportedEncodingException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     post.setEntity(formEntity); 
     try { 
      HttpResponse response = CommonClass.httpClient.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; 
    } 
    public static String makeWebCall(String url) { 
     System.out.println("=========> Response url => "+url); 
     HttpGet httpRequest = new HttpGet(url); 
     try { 
      HttpResponse httpResponse = CommonClass.httpClient.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; 
    } 
} 
Các vấn đề liên quan