5

让我描述一下我的应用程序,我从网站 JSON url (Drupal website) 获取数据,数据是 JSON 格式。在我的应用程序中,登录功能完美运行。& 用户在服务器上经过验证。我还从服务器获取其他数据(JSON url)并显示在我的 android 应用程序中。 现在,问题是我无法访问需要登录的页面的 JSON 数据,因为我的登录没有在整个 android 应用程序中维护。

我在 stackoverflow 和谷歌上搜索了这些链接并尝试了但不知道如何在我的代码中使用它们:http: //hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html

安卓会话管理

Android 中的 Http cookie 存储

这是来自 drupal 站点的空 JSON,无需登录。

{
    "nodes": []
}

这是来自 drupal 站点的 JSON -登录后( http://www.mywebsite.com/user/login ) 并重新加载站点上的页面http://www.mywebsite.com/myaccount-page - 在计算机 webbrowser中。表示计算机网络浏览器自动维护登录会话。

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

但在 android 应用程序中它不会自动执行此操作。 所以我想在 Android 中维护这个会话,这样我就可以登录到 android 应用程序,登录后重定向到另一个页面活动并在那里获取 JSON 数据。 这是我的代码:

登录活动.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);

        }
    });
 }
 }

util.java 中的 makeWebCall 方法

实用程序.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;
}

现在使用此代码登录成功,并且我从服务器获得了详细的 JSON 响应。& page-activity 重定向到用户个人资料的第二页。在第二页上,我没有得到用户配置文件 JSON 数据——如上所述,我得到的是空白 JSON,因为没有维护会话。

这是第二页活动的代码。

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

util.java 中配置文件的 makewebcall 方法

实用程序.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;
}


}

我在这个页面上得到了空白的 JSON - 我上面已经提到过。那么如何在此用户配置文件活动中维护会话并获取数据?

感谢收听。

4

2 回答 2

3

最后它为我工作:)

我没有一直使用新的DefaultHttpClient,而是将其设为静态并仅使用一次。

static DefaultHttpClient client = new DefaultHttpClient();
于 2012-06-01T11:47:34.260 回答
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 velsans@gmail.com 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;
    }
}
于 2015-11-03T05:36:15.740 回答