原生Webview白痴坑之——同步Cookie被默认缓存模式和清除缓存

起因

1.前段时间因业务所需做了个新项目:登录页+首页是原生android实现,其余详情页都是嵌套H5页面。
2.在H5页面需要用到用户信息的情况下,这样的需求存在一个问题,每次请求加载webview都需要传session去同步cookie才可以判断是否处于已登录状态,如果是未登录就走错误处理啥的(例如跳转登录页)

问题

习惯使用原生的webview,但是存在默认缓存模式,导致后台
1.不走html,直接走html的渲染
2.然后调用js
3.js里面有ajax请求
4.因为没有走html,session没有带过来,所以ajax请求的session与登录时的session不一致

导致后续没办法请求,也就是会存在只有第一次进入webview详情页的时候显示正常,第二次及以上进入都一直在加载转圈圈状态。
错误情况.gif

webview缓存

WebView中有着两种缓存:
1.网页数据缓存(存储打开过的页面及资源)
2.H5缓存(即AppCache)
webview默认缓存模式是LOAD_DEFAULT

/**
     * Default cache usage mode. If the navigation type doesn't impose any
     * specific behavior, use cached resources when they are available
     * and not expired, otherwise load resources from the network.
     * Use with {@link #setCacheMode}.
     */
    public static final int LOAD_DEFAULT = -1;
 
    /**
     * Normal cache usage mode. Use with {@link #setCacheMode}.
     *
     * @deprecated This value is obsolete, as from API level
     * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and onwards it has the
     * same effect as {@link #LOAD_DEFAULT}.
     */
    @Deprecated
    public static final int LOAD_NORMAL = 0;
 
    /**
     * Use cached resources when they are available, even if they have expired.
     * Otherwise load resources from the network.
     * Use with {@link #setCacheMode}.
     */
    public static final int LOAD_CACHE_ELSE_NETWORK = 1;
 
    /**
     * Don't use the cache, load from the network.
     * Use with {@link #setCacheMode}.
     */
    public static final int LOAD_NO_CACHE = 2;
 
    /**
     * Don't use the network, load from the cache.
     * Use with {@link #setCacheMode}.
     */
    public static final int LOAD_CACHE_ONLY = 3;

可以通过WebSettings来设置cache mode : setCacheMode。如果要设置缓存路径可以参考https://www.jianshu.com/p/f1efb0928ebc类似文章

WebSettings webSettings= webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

然后试着添加下面这句话没效果

settings.setAppCacheEnabled(false);

同步cookie

/**
     * 同步cookies
     */
    public static void synchronousWebCookies(String url, String cookies){
        if (!TextUtils.isEmpty(url))
            if (!TextUtils.isEmpty(cookies)) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                    CookieSyncManager.createInstance(MyApplication.mContext);//MyApplication.mContext传可用context即可
                }
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                cookieManager.removeSessionCookie();// 移除
                cookieManager.removeAllCookie();
                StringBuilder sbCookie = new StringBuilder();
                sbCookie.append("SESSION=" + cookies);//拼接sessionId,跟后台约好格式,例如我的是SESSION=1111111111这样传
                String cookieValue = sbCookie.toString();
                cookieManager.setCookie(url, cookieValue);//为url设置cookie
                CookieSyncManager.getInstance().sync();//同步cookie
                String newCookie = cookieManager.getCookie(url);
                LogUtils.e("同步后cookie:" + newCookie);
            }
     }

调用InfoCache.getCookie()是你的cookie,我这边是存在我自己的InfoCache类里面

synchronousWebCookies(url, InfoCache.getCookie());//直接写在loadUrl(url)之前
mWebView.loadUrl(url);

解决

但是我的问题不是如何缓存,而是清理缓存,即每次进入都清理缓存

WebView mWebView = findViewById(R.id.webView);
mWebView.clearCache(true);

如果不想每次都清理也可以选择一种合适的缓存模式,原生webview也是存在很多优化的地方,可参考https://www.jianshu.com/p/95d4d73be3d1
最终效果每次进入都可以加载完整页面,不会第二次及以上都处于转圈圈状态

最终效果.gif

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。