android WebView 和 HttpClient cookie同步

来源:互联网 发布:银联数据待遇 编辑:程序博客网 时间:2024/04/30 12:31

首先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