Can I use Android 4 HttpResponseCache with a WebView based application?

I am working on a WebView based application that currently runs on v3.1 tablets. I can't seem to get WebView to cache css, js and images (or use cache). It seems that the application is connecting to a server that returns a 304 response (HTML pages are dynamic and should always use a server).

I was wondering if the HttpResponseCache (available under v4) works with WebViewClient or if WebView should already manage the caching of HTTP resources.

Thanks.

+4
source share
1 answer

After some testing, I realized that at the Android Webkit level, URLConnection is not used for the HTTP request, which means that the HttpResponseCache cannot automatically connect to the WebView like other native scripts.

So, I tried an alternative approach: use your own WebViewClient to connect WebView and 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; } } }); 

If you need offline access to cached resources, just add the cache header:

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

BTW, for this approach to work correctly, you need to properly configure the web server response using the "Cache-Control" header with the cache.

+4
source

All Articles