WebView的Cookie跨域问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denglusha737/article/details/83684488

案例

前几天遇到这样一个问题:前端开发了一个h5页面,在webView中加载时,发现获取不到 设置的cookie信息.原以为是没设置好,将支持的一级域名梳理了一遍,循环设置;其次客户端自己测试,通过getCookie(url)能正常获取,但是抓包发现页面网络请求的cookie中并没有数据,一时非常奇怪。

继续跟踪,发现页面地址与页面中的网络请求地址,域名不一致。如页面地址www.badidu.com,页面中有多个请求,其中之一是www.chedan.com/getUserInfo,此时www.chedan.com/getUserInfo就获取不到设置的cookie信息。将页面也挂载到www.chedan.com下,访问正常。由此基本判断,是由跨域访问导致。

查看CookieManager源码,发现方法acceptThirdPartyCookies:

    /**
     * Sets whether the {@link WebView} should allow third party cookies to be set.
     * Allowing third party cookies is a per WebView policy and can be set
     * differently on different WebView instances.
     * <p>
     * Apps that target {@link android.os.Build.VERSION_CODES#KITKAT} or below
     * default to allowing third party cookies. Apps targeting
     * {@link android.os.Build.VERSION_CODES#LOLLIPOP} or later default to disallowing
     * third party cookies.
     *
     * @param webview the {@link WebView} instance to set the cookie policy on
     * @param accept whether the {@link WebView} instance should accept
     *               third party cookies
     */
    public abstract void setAcceptThirdPartyCookies(WebView webview, boolean accept);

  看文档,LOLLIPOP(21)及以上,默认不允许跨域访问cookie信息,因此设置为true即可。

其他注意

1.需要共享cookie信息,必须设置setAcceptCookie(true),意为允许存放和接收cookie.

2. removeSessionCookie():清除session信息,务必谨慎使用。shouldOverrideUrlLoading方法设置cookie时若清除了sesseion,将导致跳转后的页面获取不到前页面放在session中的信息。

3.setAcceptFileSchemeCookies:允许存放和接收 file scheme URLs 中的cookie。谨慎使用

最后贴上设置cookie的代码:

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(ProHelper.getApplication());
    }
	CookieManager cookieManager = CookieManager.getInstance();
	cookieManager.setAcceptCookie(true);// 允许接受 Cookie
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
		cookieManager.setAcceptThirdPartyCookies(webView, true);        //跨域cookie读取
	}

	String[] cookies = cookie.split(",");
	for (int i = 0; i < RegexURLUtil.WEB_COOKIE_DOMAIN.length; i++) {
		for (String cooky : cookies) {
			String[] values = cooky.split("=");
			String url_cookies = values[0] + "=" + values[1] + ";domain=" + RegexURLUtil.WEB_COOKIE_DOMAIN[i] + ";path=/";
			cookieManager.setCookie(RegexURLUtil.WEB_COOKIE_DOMAIN[i].replaceFirst(".", ""), url_cookies);
		}
	}

	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
		CookieSyncManager.getInstance().sync();
	} else {
		cookieManager.flush();
	}

  WEB_COOKIE_DOMAIN为支持的域名数组,如{".baidu.com",".chedan.com"}

猜你喜欢

转载自blog.csdn.net/denglusha737/article/details/83684488