1. load faster 2. Reduce data usage 3. relieve pressure server can also access the network when no 4., optimize the user experience
Talk about my needs: 1. When using the cache has a net short period of time, up to date, there is no net when the cache longer 2. Specify the interface generates cache files, other interfaces will not have the cache file 3. Can the drop-down refresh force a refresh
The principle
Retrofit2 implement caching is achieved by natural okhttp blocker, is particularly controlled by the Cache-Control separately as follows:
1
2
3
4
5
6
7
8
9
10
11
12
NO- Cache NO -
Cache time will be cached, but each time in response providing data to the client (browser), the cache must assess the effectiveness of the response to the cache server.
NO
-
Store
all content will not be cached in cache or temporary Internet files
max
-AGE = xxx (xxx
IS numeric
) cached content to xxx seconds after failure, this option is only
the HTTP 1.1
is available, and if and
Last
when used together -Modified, higher priority
max
-stale and
max
-AGE, can only be disposed inside the head request.
And set max -stale and
max -AGE, cache miss by the longest time count. (This fact, do not tangle)
CacheControl.FORCE_CACHE mandatory use of the cache, if the data is not cached, then throw 504 (
only -
IF -cached)
CacheControl.FORCE_NETWORK forced to use the network, without using any cache.
Simple implementation
1. first create interceptor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR =
new Interceptor() {
publicResponse (Chain chain)throws IOException {
Request request = chain.request();
Response response = chain.
proceed(request);
if (NetworkUtil.isNetworkAvalible(MyApplication.getContext())) {