2
votes

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?

1
Nothing built in will do that. There's no response for OkHttp to return, and it's always a response and headers together.Jesse Wilson
Thanks Jesse for the response, would an alternate solution be to check if the response came from disk or network and only process those from the network (i.e. for updating my database)? I don't want to keep parsing the same JSON over and over. Or am I better to implement my own cache, but that cache only stores "" along with the headers instead of the full response (in order to save space)?Andrew Kelly
@JesseWilson I guess with OkHttp3 your comment is no longer true? The code you get from square.github.io/okhttp/3.x/okhttp/okhttp3/… should cover this no?Espen Riskedal

1 Answers

4
votes

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.