【问题标题】:Can I use the Android 4 HttpResponseCache with a WebView based application?我可以将 Android 4 HttpResponseCache 与基于 WebView 的应用程序一起使用吗?
【发布时间】:2012-08-21 22:24:11
【问题描述】:

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

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

谢谢。

【问题讨论】:

标签: android caching webview


【解决方案1】:

经过一番测试,我发现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”标头。

【讨论】:

  • 有没有办法判断响应是否来自缓存?
猜你喜欢
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2010-09-09
  • 2020-08-14
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多