Hi I am trying to use the HttpResponseCache introduced in Android 4.The docs do talk clearly about how to install the cache but I am at a complete loss on how to cache Image
When you enable HttpResponseCache
, all HttpUrlConnection
queries will be cached. You can't use it to cache arbitrary data, so I'd recommend keep using DiskLruCache
for that.
In my case HttpResponseCache wasn't actually caching anything. What fixed it was simply:
connection.setUseCaches(true);
(This must be called on the HttpURLConnection
before establishing connection.)
For finer grained control, max-stale
can be used as Jesse Wilson pointed out.
From the section Force a Cache Response on the HttpResponseCache documentation:
Sometimes you'll want to show resources if they are available immediately, but not otherwise. This can be used so your application can show something while waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the
only-if-cached
directive:
try {
connection.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
} catch (FileNotFoundException e) {
// the resource was not cached
}
This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the
max-stale
directive with the maximum staleness in seconds:
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);