1

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

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

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

我认为这个解决方案对许多刚接触 android 的开发人员很有用。

4

2 回答 2

0

试试这个,它将用户名传递和会话存储到共享首选项中

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

您可以参考代码并按照您的逻辑制作应用程序

并注意下次向服务器发送请求时不要忘记在标头中添加会话/cookie

于 2012-08-22T12:32:21.107 回答
0

只是为了不让问题得不到回答并解释我是如何解决问题的,这是我的答案。

我使用了Loopj Android Async Http Client library,Instagram 和 Pinterest 等主要应用程序都在使用它。

以这种方式保持 cookie 的持久性非常简单。所有你需要的是:

AsyncHttpClient myClient = new AsyncHttpClient(); // a client instance

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore); // setting the cookie store
于 2014-02-22T04:24:54.223 回答