【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());
        }
    }


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值