【android-Webview】设置多个cookie,实现webview中保存登录信息

方法:通过重复调用 cookieManager.setCookie(url,cookie1); 来保存多个cookie。

代码:

    /**
     * Sync Cookie
     */
    private void syncCookie(Context context, String url){
        try{

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
//            cookieManager.removeSessionCookie();// 移除
//            cookieManager.removeAllCookie();
//            String oldCookie = cookieManager.getCookie(url);
//            if(oldCookie != null){
//                Log.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
//            }

            StringBuilder sb = new StringBuilder();
            sb.append(String.format("userName=%s", MySharedPreference.getLocalLoginName()));
//            sb.append(String.format(";pwd=%s", MySharedPreference.getLocalLoginPwd()));
//            sb.append(String.format(";remeberPws=%s", "1"));
            sb.append(String.format(";domain=%s", "blog.csdn.net"));
            sb.append(String.format(";path=%s","/"));
            String cookieValue1 = sb.toString();

            StringBuilder sb2 = new StringBuilder();
//            sb2.append(String.format("name=%s", "remeberPws"));
//            sb2.append(String.format(";value=%s", "1"));
            sb2.append(String.format("remeberPws=%s", "1"));
            sb2.append(String.format(";domain=%s", "blog.csdn.net"));
            sb2.append(String.format(";path=%s","/"));
            String cookieValue2 = sb2.toString();

            StringBuilder sb3 = new StringBuilder();
//            sb3.append(String.format("name=%s", "remeberPws"));
            sb3.append(String.format("pwd=%s", MySharedPreference.getLocalLoginPwd()));
            sb3.append(String.format(";domain=%s", "blog.csdn.net"));
            sb3.append(String.format(";path=%s","/"));
            String cookieValue3 = sb3.toString();

            cookieManager.setCookie(url, cookieValue1);
            cookieManager.setCookie(url, cookieValue2);
            cookieManager.setCookie(url, cookieValue3);
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){
//                Log.d("Nat: webView.syncCookie.newCookie", newCookie);
            }
        }catch(Exception e){
            Log.e("TAG", e.toString());
        }
    }


猜你喜欢

转载自blog.csdn.net/u013372185/article/details/70649728
今日推荐