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

我可以将Android 4 HttpResponseCache与基于WebView的应用程序一起使用吗?,android,caching,webview,Android,Caching,Webview,我正在开发一个基于WebView的应用程序,目前正在v3.1平板电脑上运行。我似乎无法让WebView缓存css、js和图像(或使用缓存)。应用程序似乎总是连接到服务器,服务器返回304响应(HTML页面是动态的,总是需要使用服务器) 我想知道HttpResponseCache(在v4下提供)是否可以与WebViewClient一起工作,或者WebView是否应该已经管理HTTP资源的缓存 谢谢。经过一些测试,我发现Webkit的Android层不使用URL连接进行HTTP请求,这意味着Http

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

我想知道HttpResponseCache(在v4下提供)是否可以与WebViewClient一起工作,或者WebView是否应该已经管理HTTP资源的缓存


谢谢。

经过一些测试,我发现Webkit的Android层不使用URL连接进行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服务器,使其使用启用缓存的“缓存控制”标题进行响应。

如果您需要在Android 2中使用ICS HttpResponseCache的这个后端口,您可以查看一下。x:有没有办法判断响应是否来自缓存?