Need an example of HttpResponseCache in Android

雨燕双飞 提交于 2019-11-28 21:32:18
Jesse Wilson

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);

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.

Jonik

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!