0
votes

This may be a very basic question, but I've ran out of ideas.
Retrofit v2.4.0 is not sending the If-Modified-Since header, as a result caching is not working.

I'm polling the server several times a day to see if is there any updated data, hence the need for If-Modified-Since header. (push notifications may be implemented in a new release)

Based on this article, the setup is extremely easy: https://futurestud.io/tutorials/retrofit-2-activate-response-caching-etag-last-modified
I've read several related articles, but those were focused on the use-cases when the server's implementation was either inaccessible or it didn't send the headers. This is not my case. Those suggested the usage of networkInterceptors(). As the correct response headers are sent, I shouldn't need an interceptor (I guess).

Theoretically it should work.

Based on the response headers, it looks like that the server is correctly configured.

Here's the code:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

Cache cache = new Cache(getApplication().getCacheDir(), 30 * 1024 * 1024);

httpClient = new OkHttpClient.Builder()
    .cache(cache)
    .addInterceptor(logging)
    .build();

retrofit = new Retrofit.Builder()
    .baseUrl("http://someserver:8080/")
    .callbackExecutor(Executors.newSingleThreadExecutor())
    .client(httpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Logs:

D/OkHttp: --> GET http://someserver:8080/model/modelId http/1.1
D/OkHttp: --> END GET

<-- 200 OK http://someserver:8080/model/modelId (23ms)
D/OkHttp: Cache-Control: private
D/OkHttp: Content-Length: 3240854
D/OkHttp: Content-Type: application/octet-stream
D/OkHttp: Last-Modified: Mon, 14 May 2018 07:22:25 GMT
D/OkHttp: Date: Mon, 14 May 2018 09:03:50 GMT
D/OkHttp: <-- END HTTP

Please let me know what am I doing wrong.

1
If you look at the Troubleshooting section of this article it looks like the Cache-Control header isn't setup correctly. It should be "Cache-Control: private, must-revalidate". Let me know if this helps.Wess
Yup, this solved the issue :-) Can you please post a comment so I can accept it?Robert
I've posted my answer, please accept it @RobbyWess

1 Answers

2
votes

Your server's cache configuration is incorrect. If you look at this article's Troubleshooting section you'll notice that it needs to be Cache-Control: private, must-revalidate.