Implementation of network data cache interceptor Interceptor Based on okhttp3 (supporting retrofit)
Preface: some time ago, when developing the app, it often occurred that due to the user's equipment environment, the data obtained from the network end could not be obtained, so the result displayed on the app end is always a blank box. This situation is extremely bad for the user experience, so, After thinking hard, I decided to start with okhttp (because the network request framework I used in the project is okhttp), so I wrote such a network data cache interceptor. OK, so we decided to start writing. Let me talk about the idea first:
Thoughts
Since we want to write a network data cache interceptor, which mainly uses the powerful interceptor function of okhttp, what data should we cache, or under what circumstances should we enable the data cache mechanism?
First: it supports post requests, because the official has provided a cache interceptor, but it has a disadvantage that it can only cache the data of get requests, but it does not support post.
Second: when the network is normal, it is to fetch data from the network end. If the network is abnormal, such as timeoutexception unknowhostexception, we need to cache the returned data.
Third: if the data extracted from the cache is empty, we still need to let the request go through the rest of the normal process.
Fourth: the caller must fully control the caching mechanism, and can selectively decide whether to cache the data according to their own business needs.
Fifth: the use must be simple, which is the most important point.
OK, we listed five points above, which is our general idea. Now let's talk about the code:
Code article
Caching framework: the caching framework I use here is disklrucache https://github.com/JakeWharton/DiskLruCache This caching framework can be stored locally and approved by Google, which is the main reason for choosing this framework. I also encapsulate the cache framework here with a CacheManager class:
Demo address: https://github.com/xiaolei123/OkhttpCacheInterceptor