Need an example of HttpResponseCache in Android

后端 未结 3 1610
天涯浪人
天涯浪人 2020-12-14 22:48

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

相关标签:
3条回答
  • 2020-12-14 23:31

    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.

    0 讨论(0)
  • 2020-12-14 23:32

    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.

    0 讨论(0)
  • 2020-12-14 23:34

    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);
    
    0 讨论(0)
提交回复
热议问题