How do you turn on OkHttp's response Cache in an Android app, and what do CacheControl.FORCE_CACHE and CacheControl.FORCE_NETWORK change for a request?
answer
- off until you configure it
- a directory and a size
- only-if-cached means 504 on a miss
- no-cache versus max-age=0
basics
~20 sPass a Cache(directory, maxSize) to OkHttpClient.Builder().cache(); OkHttp then stores cacheable GET responses following the server's headers. FORCE_CACHE allows only cached data and returns a 504 when nothing usable exists; FORCE_NETWORK skips the cached copy and fetches from the server.
solid answer
~40 sOkHttp's cache is **off by default**. You enable it with `OkHttpClient.Builder().cache(Cache(File(context.cacheDir, "http_cache"), 50L * 1024 * 1024))`, and the directory must belong to that one `Cache` instance. It then follows the server's caching headers: fresh responses are served from disk, stale ones are revalidated with `If-None-Match` or `If-Modified-Since`, and by default only `GET` responses are stored, and only once the body has been read fully. Per request, `cacheControl(CacheControl.FORCE_CACHE)` means *only if cached*, accepting any staleness: if nothing usable is stored, OkHttp returns a synthetic `504`. `CacheControl.FORCE_NETWORK` is `no-cache`: it ignores the stored copy and downloads a full response. When you only want the cached copy checked, `maxAge(0)` is cheaper, because it revalidates and can get a `304`.
code
kotlin · 22 linesimport android.content.Context
import java.io.File
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import okhttp3.Request
fun buildClient(context: Context): OkHttpClient =
OkHttpClient.Builder()
.cache(Cache(File(context.cacheDir, "http_cache"), 50L * 1024L * 1024L))
.build()
fun cachedCatalogOrNull(client: OkHttpClient): String? {
val request = Request.Builder()
.url("https://api.example.com/catalog")
.cacheControl(CacheControl.FORCE_CACHE)
.build()
client.newCall(request).execute().use { response ->
if (response.code == 504) return null // nothing usable on disk
return response.body?.string()
}
}go deeper
Recall that the cache is off until you pass a Cache with a directory and size, and that FORCE_CACHE means cached data only.
Explain what OkHttp stores, how stale entries are revalidated, and what FORCE_CACHE, FORCE_NETWORK and maxAge(0) each do to one request.
Diagnose a cache that never hits: unread bodies, missing headers, no-store, and why a header rewrite must run below the cache stage.
Decide what the app caches on disk at all, which screens may show stale data offline, and how much storage the cache may claim.
## Turning the cache on OkHttp ships a disk cache for HTTP and HTTPS responses, but it is **optional and off by default**. You opt in by giving the client a `Cache`: - **A directory** that belongs to this one `Cache` instance alone. Two `Cache` objects on one directory can corrupt it. One `Cache` may be shared by several clients, which `newBuilder()` does automatically. - **A maximum size in bytes.** OkHttp evicts the least recently used entries beyond it. The project's own example uses 50 MiB in the app's cache directory, which Android may clear when storage runs low. On Android, `context.cacheDir` is the usual home, so the cache survives app restarts but stays disposable. ## What gets stored The cache aims to be correct by the HTTP caching rules and pragmatic where they are vague. In OkHttp terms: - **Only `GET` responses are stored by default.** A `POST`, `PUT`, `PATCH`, `DELETE` or `MOVE` instead removes any stored entry for that URL. Since OkHttp 5.0, `Request.Builder.cacheUrlOverride()` lets an app give a request its own cache key, and a `POST` with an override can be cached; the body is not part of the key, so the override URL must encode whatever makes the response distinct. - **The response must allow it.** A `no-store` directive on the request or response prevents storage, a `Vary: *` response is never stored, and partial responses are not cached. - **The body must be read fully.** A response that the app closes early, cancels or stalls on is not written. This is the first thing to check when a cacheable response never shows up as a hit. - **Freshness comes from the server.** `max-age` or `Expires` decide how long an entry is fresh. Without them, OkHttp applies a heuristic of 10% of the document's age from `Last-Modified`, except for URLs with a query string. When a stored entry is stale, OkHttp sends a **conditional request** with `If-None-Match` or `If-Modified-Since`. A `304 Not Modified` reply means the stored body is reused and only headers travel. The resulting `Response` has both `cacheResponse` and `networkResponse` set, and the cache counts it as a network use and a hit. ## Steering a single request `Request.Builder().cacheControl(...)` sets request directives. The two constants cover the common cases: | Request directive | What OkHttp does | |---|---| | `CacheControl.FORCE_CACHE` (`only-if-cached` plus unlimited `max-stale`) | serves the stored response even when stale; if none is usable, returns a synthetic `504` with the message `Unsatisfiable Request (only-if-cached)` | | `CacheControl.FORCE_NETWORK` (`no-cache`) | ignores the stored copy and makes a full request; the new response may still be stored | | `CacheControl.Builder().maxAge(0, TimeUnit.SECONDS)` | treats the stored copy as stale, so OkHttp revalidates it and may reuse its body after a `304` | | `CacheControl.Builder().maxStale(...)` | accepts a stored response that has been stale for up to the given time | Two practical patterns follow: 1. **Show something offline first.** Issue the request with `FORCE_CACHE`, render it if the code is not `504`, then refresh with a normal request. 2. **Pull to refresh.** Use `FORCE_NETWORK` when the server must send a complete new body, or `maxAge(0)` when a cheap revalidation is enough. ## Seeing what happened - `response.cacheResponse` and `response.networkResponse` tell you whether disk, network or both produced a response. - `Cache.requestCount()`, `networkCount()` and `hitCount()` give totals for the cache's lifetime. - An `EventListener` receives `cacheHit`, `cacheMiss` and `cacheConditionalHit` events per call. - `cache.evictAll()` clears every entry, and the `cache.urls()` iterator removes individual ones. ## Mistakes that keep the cache empty or wrong - **A new `Cache` per client build.** Every client built that way opens another `Cache` on the same directory, which can corrupt it or fail at runtime. Build the `Cache` once, with the shared client. - **Expecting freshness the server never granted.** A response with no `max-age`, `Expires` or `Last-Modified` is stored but never fresh, so a normal request still goes to the network; only `FORCE_CACHE`, with its unlimited `max-stale`, will serve it. - **Clearing data on sign-out.** `evictAll()` drops every entry and keeps the cache usable; `delete()` closes the cache and deletes every file in its directory, including files the cache did not create. ## When the server's headers are wrong If a server omits caching headers, the right fix is on the server. As a stopgap, OkHttp's interceptor guide shows rewriting a response's `Cache-Control` in an interceptor, and warns that it is dangerous. To influence what gets **stored**, that rewrite must run in a network interceptor, because the cache stage sits above the network interceptors and below the application ones.
- A GET response carries Cache-Control: max-age=600, yet the next identical request still hits the network. What do you check first?Whether the app read the first response body fully. OkHttp writes an entry only as the body streams through, so a body that was closed early, canceled or stalled is not stored. Then check that a `Cache` is configured on the client that made the call, that neither side sent `no-store` or `Vary: *`, and confirm the miss by checking that `response.cacheResponse` is null on the second call.
- Why can FORCE_CACHE still return a 504 when an entry for the URL exists on disk?`FORCE_CACHE` combines `only-if-cached` with unlimited `max-stale`, so any stored response is acceptable unless serving it would require contacting the server. A stale response marked `must-revalidate`, or any response marked `no-cache`, needs validation, so OkHttp cannot use it without the network and returns the synthetic `504 Unsatisfiable Request (only-if-cached)`.
- OkHttp caches responses automatically as soon as a client is built.
- FORCE_CACHE throws an IOException when nothing is cached.
- FORCE_NETWORK sends a conditional request and reuses the body after a 304.
- OkHttp caches a plain POST response whenever the server sends max-age.
- Two Cache instances can safely share one directory.
Assumes OkHttp 5.5; Request.Builder.cacheUrlOverride(), which lets a POST be cached under its own key, first appeared in the 5.0 alphas and is absent from OkHttp 4.12, which Retrofit 3.0.0 depends on.