androidokhttpetagif-none-match

Android OkHttp how to handle ETag


I'm try to do Android offline caching method using OkHttp. The flow is like this:

  1. I send an HTTP request with an ETag empty string at header field if-none-catched to the server, and the server returns a proper ETag.
  2. Then I store the ETag and cache the response.
  3. Next time when I fire the same service call I get the same ETag and set it to the HTTP request header and the server will return HTTP 304 if the ETag is the same.

My issue now is how can I store and retrieve the ETag? Does OkHttp default will handle or I need store at SQLite? I keep looking on Google about OkHttp implement ETag sample code but all I get is just normal caching method. Link I refer:

  1. I'm trying to use Java's HttpURLConnection to do a "conditional get", but I never get a 304 status code
  2. https://github.com/square/okhttp/wiki/Interceptors
  3. Correct way of setting up cache for OkHttp in Android
  4. https://gist.github.com/polbins/1c7f9303d2b7d169a3b1#file-restcontroller-java-L45

so far what I achieved is only cache for 1st time service call, but never get latest data from server anymore. Appreciate if anyone can provide some guidance or found any good example of handle ETag and if-none-catch dynamically for OkHttp to share with. Any clarification feel free to ask.


Solution

  • You just need to enable OkHttp’s response cache. It’ll use the ETag if your webserver returns one.