首页 > android webview 打开远程页面时,怎样把某些资源文件的request url 替换为本地assets资源。

android webview 打开远程页面时,怎样把某些资源文件的request url 替换为本地assets资源。

目的是为了提高加载速度。比如jquery可以预先放置在app assets。把远程页面中的/sss/jquery.js文件在发起请求前映射到本地android_asset/jquery.js文件。

在ios中我可以用 LocalSubstitutionCache.mappingDict 做到。在android中一直找不到解决方案。

前提是不能修改远程页面的代码,不能在远程页面中使用“file:///android_asset”之类的资源路径。


问一下 你的 webview 页面里如何加载的assets 目录里的文件呢,???


WebView从API 11提供了一个回调就是用来处理类似的需求。即shouldInterceptRequest

 public WebResourceResponse shouldInterceptRequest(WebView view,  String url) {
    Log.i(LOGTAG, "shouldInterceptRequest url=" + url + ";threadInfo" + Thread.currentThread());
    WebResourceResponse response = null;
    if (url.contains("logo")) {
        try {
            InputStream localCopy = getAssets().open("droidyue.png");
            response = new WebResourceResponse("image/png", "UTF-8", localCopy);
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
    return response;
}    

详情可以参考这篇文章,Android中WebView拦截替换网络请求数据

【热门文章】
【热门文章】