You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OkHttp缓存工作原理解析及单例客户端缓存目录冲突咨询

Great question—especially since you’re making the switch to a singleton OkHttp client (smart call, that’s going to save you a ton of overhead and those cache conflicts the docs warned about). Let me break down exactly how OkHttp’s caching works, step by step:

OkHttp Cache: Under the Hood

1. First, It’s All About HTTP Rules

OkHttp doesn’t invent its own caching logic—it strictly follows standard HTTP caching headers. That means:

  • Only responses the server explicitly allows to be cached (via Cache-Control, Expires, ETag, etc.) get stored.
  • POST requests are not cached by default (unless the server adds specific cache headers to permit it), but GET/HEAD requests are fair game if the server gives the green light.

2. The Cache Directory: Files & Structure

When you set up a cache, you pass a disk directory and a max size (like new Cache(new File(getCacheDir(), "okhttp-cache"), 10 * 1024 * 1024) for a 10MB cache). Here’s what happens inside that directory:

  • Each cached response gets split into two files:
    • An index file: Stores metadata—request URL, cache headers, timestamps, and a pointer to the actual data file.
    • A data file: Holds the raw response body (the actual content you’re fetching).
  • These files are named with hashes to avoid collisions, but here’s the catch: if multiple OkHttp clients use the same directory, they’ll overwrite these files without checking if another client is using them. That’s why the docs warn about crashes—corrupted cache data breaks everything.

3. What Happens When You Make a Request?

Let’s walk through the cache lookup flow for a typical GET request:

  1. OkHttp first checks if there’s a cached response that’s still "fresh" (per Cache-Control rules like max-age). If it is, you get the cached response instantly—no network call needed.
  2. If the cached response is stale (expired), OkHttp sends a conditional request to the server. This includes headers like If-None-Match (using the cached ETag value) or If-Modified-Since (using the cached last-modified timestamp).
  3. The server will either:
    • Send a 304 Not Modified response: OkHttp updates the cached response’s freshness and returns it to you.
    • Send a full new response: OkHttp replaces the old cached entry with this new one and returns it.

4. Customizing Cache Behavior

You don’t have to stick to the defaults. Use CacheControl builders to tweak how caching works:

  • Force a network request even if a fresh cache exists: CacheControl.FORCE_NETWORK
  • Force using a stale cache if there’s no network (great for offline support): CacheControl.FORCE_CACHE
  • You can also add custom interceptors, but the default CacheInterceptor that comes with OkHttp handles most standard cases perfectly.

5. Singleton Client & Cache Safety (Why Your Change Matters)

Since you’re moving to a singleton client, this is how you avoid those cache crashes:

  • Initialize the cache once when you create the singleton client. All requests go through this single client, so it coordinates access to the cache files—no more overwriting conflicts.
  • Never let another OkHttp client (even a temporary one) use the same cache directory. Stick to the singleton, and your cache will stay intact.

内容的提问来源于stack exchange,提问作者Kushan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:01:58