android WebView 和 HttpClient cookie同步

首先android5.0 实现了WebView与 框架的自动cookie同步,无需额外操作。

5.0一下版本需要手动同步cookie

方法如下

<pre name="code" class="java">CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.removeAllCookie();
    List<Cookie> cookies = new PersistentCookieStore(context).getCookies();
    for (Cookie cookie : cookies) {
      //注意这里为什么放肆的写了个cookie.getDomain(),而不是像api里边说的url,类似baidu.com如果是域名,直接设置“baidu.com“,
      cookieManager.setCookie(<span style="color:#ff0000;">cookie.getDomain()</span>,  cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain() + "; path=" + cookie.getPath());
    }
    CookieSyncManager.getInstance().sync();

 

这涉及到了cookie的知识,设置cookie时,会先检测cookie的Domain是否和url网址的域名一致,如果不一致设置cookie失败。

所以url在里边起到作用,就是检测Domain域名, 设置在这个域名下的所有url的请求的cookie。

如果是设置一个设置二级的url,反倒不容易理解。

看看google api注释:

  /**
     * Sets a cookie for the given URL. Any existing cookie with the same host,
     * path and name will be replaced with the new cookie. The cookie being set
     * must not have expired and must not be a session cookie, otherwise it
     * will be ignored.
     *
     * @param url the URL for which the cookie is set
     * @param value the cookie as a string, using the format of the 'Set-Cookie'
     *              HTTP response header
     */
    public void setCookie(String url, String value) {
        throw new MustOverrideException();
    }
  url the URL for which the cookie is set ,如果不了解cookie的原理,这让解释更容易让读者理解为,只是设置了这个子url的cookie 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值