Android 12对WebView中Cookie的适配

1,096 阅读2分钟

问题描述:

最近在做Android 13适配的过程中,遇到升级后WebView加载h5网页,在设置cookie之后,h5页面发送网络请求后,无法将设置的cookie传递给后端。

原因:

从 Android官网搜索结果显示:

881684921225_.pic.jpg

由于我们的项目中的h5页面是放在assets目录下,当用WebView加载网页的时候,使用file:///android_asset/xxx/index.html 的方式进行加载,所以会涉及到跨域访问的情况,使得cookie无法传递到后端,所以解决方案从这方面下手,更改加载方式。

解决方案:

使用Android官方提供的WebViewAssetLoader类进行加载,具体方案如下:

  1. 在项目中引入配置
implementation 'androidx.webkit:webkit:1.4.0'

2. 在WebView初始化设置的时候创建WebViewAssetLoader类(注:在loadUrl之前进行)

WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
        .setDomain(domain)
        .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
        .build();

注:domain为设置cookie的时候设置的url,例如,使用CookieManager调用setCookie方法传入的url为www.baidu.com 在设置domain的时候地址也要配置为www.baidu.com 。

  1. 为WebView设置setWebViewClient并复写shouldInterceptRequest方法,如下
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    return mWebViewAssetLoader.shouldInterceptRequest(request.getUrl());
}
  1. 修改loadUrl传入的值,之前的写法为
webView.loadUrl("file///android_asset/xxx/index.html");

修改之后的写法为(其中的domain为你初始化设置的domain):

webView.loadUrl("https://{domain}/assets/xxx/index.html");

备注:

如果项目中没有涉及cookie的设置,初始化的domain可以不做设置,在loadUrl的时候url的domain配置为appassets.androidplatform.net,完整的url为:appassets.androidplatform.net/assets/xxx/…

项目中最近遇到一个棘手的问题,就是用这种方式设置之后,在另外的一个项目中并没有生效,直接404,网页无法加载出来,最后经过排查发现是域名有问题,也就是说,初始化WebViewAssetLoader设置的domain和应用的baseUrl以及cookie中的domain是必须一致的,如果这三个有一个不一致都会导致网页无法加载。