Okhttp custom interceptor (CACHE interceptor) in Android
Okhttp custom interceptor (CACHE interceptor) in Android
preface:
There is no cache for new company projects. My God, pit user traffic, isn't it. I don't know if anyone likes an interface. It's OK to click here and there. What should I do? One word "plus".
Due to the network request of the project, I changed it to retrofit. The network request of retrofit is based on okhttp by default
The cache of okhttp is determined by the returned header. If the server supports caching, there will be this sentence in the returned headers
Time here is a length of time in seconds. This means the aging of the cache. For example, set the aging of the API to one day
The returned header should be
Unfortunately. The company's server does not support caching. How can you tell? Because our returned headers contain these
But we want to use cache again. What should we do at this time., Thanks to the interceptor mechanism of okhttp, all configurations can become so simple and elegant.
We can intercept headers in the interceptor and remove the default cache control
However, we know that some data returned by the API is suitable for caching, while others are not. For example, information lists with high update frequency cannot be cached, while data such as information details can be cached. So we can't write it uniformly. Dynamic configuration is required.
Similarly, we also make articles in the header to customize a header. Note that this header must not be used elsewhere, or the value will be overwritten. Here, we define the key name of the header as cache time. Let's get this header in the interceptor. If a non null value is obtained, it indicates that the request is to support caching, and the cache time is the value corresponding to cache time. We added him.
Custom cache interceptor
After the cache interceptor is defined, we also need to configure the cache path. Here we define a cached content provider
Through the above code, we can see that we have specified the cache size of 10MB. If the amount of cached data is greater than this value, lur rules will be used internally for deletion.
Let's start configuring okhttpclient
Well, now if we need to cache data, we can cache the current data for one day by adding a header ("cache time", "3600 * 24") to the request
Thank you for reading, hope to help you, thank you for your support to this site!