androidkotlinokhttp

Custom cache OkHttp


I'd like to cache API request in my app so that user could see something even if they are offline.

I also have a HeaderInterceptor with multiple headers, such as language such as en, es, fr etc... The same endpoint returns different result depending on the header language.

From what I've read in the OkHttp source code, cache only cares about the url, so even if my user changes language and a new request is made a different header, he'll get the cache response instead of a making a new call.

How can I create a custom cache that will take into account header as well ?


Solution

  • You server should be setting a Vary header

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary

    If you apply your header in an application interceptor, OkHttp should honour the Vary header