square / okhttp

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.
https://square.github.io/okhttp/
Apache License 2.0
45.91k stars 9.16k forks source link

Customize cache #8564

Closed yoobi closed 3 weeks ago

yoobi commented 3 weeks ago

For tracking purpose here is the SO post https://stackoverflow.com/questions/79141053/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 with a different header, the user will get the cache response instead of a making a new call.

Would it be possible to create an interface of the Cache so we could make a custom one ? As pointed out in the SO post, so far it's only language header but it could be one or more header later on

NB: Possible workaround would be to add the headers in the URL to use OkHttp native cache

yschimke commented 3 weeks ago

Answered on stack overflow, Vary header should be honoured. If not, it's a bug.

The option of a cache key override is the backup if your server won't support this.

But Cache won't be opened up as an interface based on previous decisions.

yoobi commented 3 weeks ago

Didn't see in the source code vary was used ! Thank you I'll ask the one in charge of the server to add theses headers :) I'll accept your answer on stack overflow as well

yschimke commented 3 weeks ago

Please reopen if it isn't working or you find bugs