Search code examples
http-headersokhttphttp-caching

Why does OkHttp cache responses with expires -1 header?


I am contacting a server using OkHttp and the server responds with a 200 OK response with a header of expires: -1. OkHttp seems to place this in the cache because when I later send the same request again but with a different header it adds an if-modified-since header to my request. The new header I added should cause the server to respond differently, but instead it responds with a 304 Not Modified. This causes OkHttp to use the cached response which is actually not the same as what the server would respond with if OkHttp didn't add the if-modified-since header. Why does OkHttp add the first response to the cache when it has an expires: -1 header?

I tried: send a request to a server, then later send the same request with a different header

I expected: server sends a different response the second time, because of the different header

What resulted: the server sent back 304 Not Modified because OkHttp added if-modified-since to my second request


Solution

  • I believe this is a bug in OkHttp. The library is incorrectly ignoring this header when it is not a date, and instead it should be immediately expiring the response.

    Please open an issue in the OkHttp bug tracker so we can fix it: https://github.com/square/okhttp/issues/new?labels=bug

    To work around, write a network interceptor that detects this header in a response and adds a Cache-Control: max-age=0 header when it is found. A similar interceptor is here: https://square.github.io/okhttp/features/interceptors/#rewriting-responses