在http请求android上保持应用程序与cookie同步

时间:2013-11-13 06:42:56

标签: android

我已成功检索并在我的共享偏好中存储了一个Cookie。使用下面的post方法:

public static void postData() throws JSONException {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Constant.CONNECTION_URL);
        ResponseHandler<String> resonseHandler = new BasicResponseHandler();

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("login",""));
            nameValuePairs.add(new BasicNameValuePair("pass",""));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            response = httpclient.execute(httppost,resonseHandler);

            JSONObject obj = new JSONObject(response);
            success = obj.get("success").toString();
            fname=obj.get("fname").toString();

            if (success.equalsIgnoreCase("1")){
                //connection successfull
                login_success_status.SavePreferences("login_success_status", success);
                login_success_fname.SavePreferences("login_success_fname",fname);
                List<Cookie> cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
                CookieSyncManager.getInstance().sync();

                cookie_name.SavePreferences("cookie_name",cookies.toString());

现在我需要使用另一个url和存储在sharepreference中的cookie再次调用webservice。如何使用带有此cookie的http进行呼叫,如何在我的应用程序中保持cookie的活动状态。

1 个答案:

答案 0 :(得分:0)

当您登录到服务器时会发生什么,在客户端和服务器之间创建一个会话,您将在cookie中获得该会话ID。此会话ID在一段时间内有效,该时间段由服务器设置,一旦您从应用程序注销此会话已过期,并且对下一次调用不再有效。如果您使用网上银行,您可能知道您在登录后的某个时间保持偶像。当您在一段时间后单击任何选项时,它会说您的会话已过期并重定向到登录页面。一旦您退出应用程序,同样的情况就在这里。一旦它过期,以前的cookie就没用了。所以在共享偏好中持久存储cookie没有任何好处。

1)将List<Cookie> cookies声明为public static

public static List<Cookie> cookies ;

2)无需在共享偏好中编写cookie

HttpClient httpclient = new DefaultHttpClient();
        if (cookies != null) {
            int size = cookies.size();
            for (int i = 0; i < size; i++) {
                httpclient.getCookieStore().addCookie(cookies.get(i));
            }
        }
        HttpPost httppost = new HttpPost(Constant.CONNECTION_URL);
        ResponseHandler<String> resonseHandler = new BasicResponseHandler();

3)在这里更新

if (success.equalsIgnoreCase("1")){
                //connection successfull
                login_success_status.SavePreferences("login_success_status", success);
                login_success_fname.SavePreferences("login_success_fname",fname);
cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();