我可以将Android 4 HttpResponseCache与基于WebView的应用程序一起使用吗?

时间:2012-08-21 22:24:11

标签: android caching webview

我正在开发一个基于WebView的应用程序,该应用程序目前在v3.1平板电脑上运行。我似乎无法让WebView缓存css,js和图像(或使用缓存)。应用程序总是似乎连接到服务器,它返回304响应(HTML页面是动态的,总是需要使用服务器)。

我想知道HttpResponseCache(在v4下可用)是否适用于WebViewClient,或者WebView是否应该已经管理了HTTP资源的缓存。

感谢。

1 个答案:

答案 0 :(得分:4)

经过一些测试,我发现Webkit的Android层没有使用URLConnection进行HTTP请求,这意味着HttpResponseCache不能像其他原生场景一样自动挂钩到WebView。

所以我尝试了另一种方法:使用自定义WebViewClient来桥接WebView和ResponseCache:

webview.setWebViewClient(new WebViewClient() {
    @Override public WebResourceResponse shouldInterceptRequest(final WebView view, final String url) {
        if (! (url.startsWith("http://") || url.startsWith("https://")) || ResponseCache.getDefault() == null) return null;
        try {
            final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.connect();
            final String content_type = connection.getContentType();
            final String separator = "; charset=";
            final int pos = content_type.indexOf(separator);    // TODO: Better protocol compatibility
            final String mime_type = pos >= 0 ? content_type.substring(0, pos) : content_type;
            final String encoding = pos >= 0 ? content_type.substring(pos + separator.length()) : "UTF-8";
            return new WebResourceResponse(mime_type, encoding, connection.getInputStream());
        } catch (final MalformedURLException e) {
            e.printStackTrace(); return null;
        } catch (final IOException e) {
            e.printStackTrace(); return null;
        }
    }
});

当您需要离线访问缓存资源时,只需添加缓存标头:

connection.addRequestProperty("Cache-Control", "max-stale=" + stale_tolerance);

顺便说一句,要使此方法正常工作,您需要正确设置Web服务器以响应启用缓存的“Cache-Control”标头。