Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 233
cloud Avatar asked Apr 25 '16 08:04

cloud


People also ask

What is the difference between retrofit and OkHttp?

Retrofit vs. OkHttp The reason is simple: OkHttp is a pure HTTP/SPDY client responsible for any low-level network operation, caching, request and response manipulation, and many more. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp.

What is ETag in REST API?

An entity tag, or ETag, is a mechanism that is provided by the HTTP protocol so that a browser client or a script can make conditional REST requests for optimistic updating or optimized retrieval of entities.

Can I delete OkHttp cache?

Deleting the cache when it is no longer needed can be done.

Does retrofit support caching?

Note that the cache header can be controlled dynamically in Retrofit instead with @Header("Cache-Control") String cacheControl parameter.


1 Answers

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

like image 111
Jesse Wilson Avatar answered Oct 24 '22 13:10

Jesse Wilson