How Android HTTP cache is working?
Asked Answered
K

1

12

I been investigating Picaso, image downloading and caching library for Android. And I found out that their caching mechanism is based on Android HttpResponseCache. The documentation says:

To measure cache effectiveness, this class tracks three statistics:

  • Request Count: the number of HTTP requests issued since this cache was created.
  • Network Count: the number of those requests that required network use.
  • Hit Count: the number of those requests whose responses were served by the cache.

So how exactly Android Http cache is working?

  • How Android knows to cache or not to cache a file, and for how long?
  • When exactly the cache is been cleaned, and by who?
  • How can I override the default http caching mechanism with my own? And should I?
Koressa answered 25/6, 2014 at 14:21 Comment(0)
M
11

Answers are below.

1) How Android knows to cache or not to cache a file, and for how long?

The HttpResponseCache caches an HTTP or HTTPS response if all of the following is true

  • It was installed via HttpResponseCache.install()

  • setUseCaches(true)was called on the HttpURLConnection or HttpsURLConnection

  • The headers returned by the HTTP/HTTPS server allow caching. See the ResponseHeaders.isCacheable() implementation for the nitty-gritty details.

The cache uses a LRU strategy replacing older cached responses with newer ones to make sure it does not exceed the allotted disk size.

2) When exactly the cache is been cleaned, and by who?

If the cache is initialized with a directory in Context.getCacheDir() or Context.getExternalCacheDir() then the files are usually deleted when the app is uninstalled. The cache can be deleted manually by calling HttpResponseCache.delete()

3) How can I override the default http caching mechanism with my own? And should I?

See HttpResponseCache.install(). If your app loads of cacheable resources via HTTP or HTTPS and does not have its own caching layer then you should consider using it. The Android default HttpResponseCache implementation should work fine.

Please note that by default no cache is used. You need to install one with HttpResponseCache.install().

Mathamathe answered 29/6, 2014 at 12:34 Comment(3)
And Picasso sets the default cache here github.com/square/picasso/blob/master/picasso/src/main/java/com/…Snare
Actually HttpResponseCache.install says nothing about how to "override the default http caching mechanism" (3). Or were you pointing to the source? Instead I would point to ResponseCache.setDefault.Syllepsis
How can I obtain value of ETag from cache?Nomination

© 2022 - 2024 — McMap. All rights reserved.