我能否在基于WebView的应用程序中使用Android 4 HttpResponseCache?

4
我正在开发一款基于WebView的应用程序,目前在运行v3.1平板电脑上。我似乎无法让WebView缓存css、js和图片(或使用缓存)。该应用程序似乎总是连接到服务器,服务器返回一个304响应(HTML页面是动态的,必须始终使用服务器)。
我想知道HttpResponseCache(在v4中可用)是否与WebViewClient一起工作,还是WebView应该已经管理HTTP资源的缓存。
谢谢。

如果您需要在Android 2.x中使用它,可以查看ICS HttpResponseCache的此回溯版本:https://github.com/candrews/HttpResponseCache - Oasis Feng
1个回答

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”头。


有没有办法判断响应是否来自缓存? - Grantland Chew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接