java - Android 使用 cookie 保持登录状态以获取 json 数据

标签 java android json cookies

到目前为止,已经以不同的方式提出了这个问题,但我无法找到此特定问题的解决方案。

简短版本: 我正在寻找一种从需要身份验证的 URL 获取 json 的方法。我希望它存储收到的 cookie,而不是每次都进行身份验证,这样就不必重新登录,并且在后续连接时保持登录状态。

长版: 基本上,我希望应用程序存储用户的用户名和密码(作为具有共享首选项的内部私有(private)字符串)。然后,它会调用登录 URL 进行身份验证并保持登录状态(获取 cookie)。完成此操作后,我希望程序从不同的 url 获取 json 数据(例如,需要用户通过 cookie 登录)。我希望即使在应用程序暂停或销毁后,它也能保持不变。 它可以被认为是类似于 chrome 插件的想法,可以在登录后简单地从网站获取数据。

我认为这个问题的解决方案对于许多刚接触 android 的开发人员来说是有用的。

最佳答案

尝试一下,它将用户名通行证和 session 存储到共享首选项中

   app_preferences =    PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    userid=app_preferences.getLong("userid",0);
    username=app_preferences.getString("username", "");

    password=app_preferences.getString("password", "");


    session=app_preferences.getString("session", "");





class task extends AsyncTask<String, integer, Boolean>{
    //httpreqclass htrq= new httpreqclass();

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        showProgressDialog();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        String usr=params[0];
        String p=params[1];
        String data[]=new String[2];
    String ur=  "http://192.168.1.45/Android.asmx/Login";

        // TODO Auto-generated method stub
    data=   postData(usr,p,ur);

    boolean sucess=false;
    try {
        JSONObject jso = new JSONObject(data[0]);
        sucess =jso.getBoolean("isSucceeded");
        if (sucess) {
              SharedPreferences.Editor editor = app_preferences.edit();

            JSONObject jsr=  jso.getJSONObject("result");
            Long a= jsr.getLong("Id");
            editor.putLong("userid", a);
                editor.putString("username", usr);
                editor.putString("password", p);
                editor.putString("session", data[1]);

             editor.commit(); // Very important

        }

    }catch (Exception e){

    }

        return sucess;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
    here put code what you want to do next


    }



}

public String[] postData(String u, String p,String url) {
    String asp = null,data = null;
    String[] rtrn=new String[2];

    //Log.e("i entrd here", "");


    try {
     HttpClient httpclient = new DefaultHttpClient(getHttpParams());
            HttpPost httppost = new HttpPost();
           HttpResponse response;
           List<NameValuePair> params = new ArrayList<NameValuePair>();                
           params.add(new BasicNameValuePair("EmailId", u));
           params.add(new BasicNameValuePair("PassWord", p));                    
           UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);

    httppost.setEntity(ent);
            response = httpclient.execute(httppost);
            Header[] headers;
         headers = response.getHeaders("Set-Cookie");
            //Header atha= respone.getFirstHeader("PHPSESSID");
             List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();

             if (cookies.isEmpty()) {
                Log.d("TAG","no cookies received");
             } else {
                for (int i = 0; i < cookies.size(); i++) {

                    if(cookies.get(i).getName().contentEquals("ASP.NET_SessionId")) {
                     asp = cookies.get(i).getValue();
                   }
                }
                Log.e("this is the cookiee", asp);
                }  





               HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                       while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                      is.close();
                      Log.e("", sb.toString());
                      rtrn[0]=sb.toString();
                      rtrn[1]=asp;


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    return rtrn;

 }



private HttpParams getHttpParams() {

        HttpParams htpp = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(htpp, 3000);
        HttpConnectionParams.setSoTimeout(htpp, 5000);

        return htpp;
    }

您可以引用代码并按照您的逻辑进行应用

请注意,下次向服务器发送请求时,不要忘记在 header 中添加 session /cookie

关于java - Android 使用 cookie 保持登录状态以获取 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12073143/

相关文章:

java - 尽管使用共享首选项,如何保存cardView单击事件状态以保存其颜色

安卓架构组件 : bind to ViewModel

Android- ScrollView 和水平回收 View 之间的滑动冲突

javascript - 如何在reactjs组件中在浏览器上呈现JSON列表?

java - Jackson:InvalidFormatException:无法从字符串值构造 java.util.Date 的实例

android - 无法完成 Retrofit 请求?

java - 过滤ArrayList并删除不需要的元素

java - Mysql驱动本身是否实现了DataSource接口(interface)?

java - 同步到要实例化的对象

android - 使用 css 禁用移动滚动