Search code examples
retrofitetaglast-modifiedhttp-cachingokhttp

In okhttp I'd like to handle Last-Modified and ETags but without caching the whole response


I'm using okhttp and Retrofit to call a REST service. The data that is returned from that service is store in my Android app inside an sqlite database.

Whenever I call the REST api, if the data hasn't changed (determined by either ETag or Last-Modified header) I want to have the Retrofit callback do nothing (data in DB is ok). Otherwise I want to download the updated JSON from the REST service and update the database (via the onSuccess method of my callback).

The okhttp examples on caching all setup disk caches for the responses, I just need to cache/store the Etag/last-modified time of each request (and not the whole response).

Should I be doing this through a custom Cache implementation that I pass to okhttp, or is there a better interface I should be using with okhttp or Retrofit?

Once I have the implementation setup do I just need to handle the 304 "errors" in my onFailure callback and do nothing?


Solution

  • To know if you've got a 304 as response, in the onResponse callback you can catch it as follows:

    if (response.raw().networkResponse().code() == 304){
        // Do what you want to do
    }
    

    At least, this is when you are using Retrofit 2 and okHttp 3. Not sure about earlier versions, but I guess it would be kind of the same? You could always try to find a 304 response when setting breakpoints in the response.