Premise:

Haven’t done network cache this aspect of the function, so want to learn. Read a lot of articles on the Internet, but also watched part of the video. I want to share some of my little heart virtues. How can I help someone in a small way, that means something to me. Without further ado. Let’s get down to business.

1. Network request

The web requests were made using Retrofit. Those of you who have used it know the advantages. It is good to write according to the illustration or Demo that has not been used, and the article on the net is a lot of, I will not repeat.




Network request writing

2. Add a cache

The key point is to see a lot of caching methods on the Internet. In the end, OkHttp adds interceptors. It seems to be the most popular method.

Let me show you two pictures to illustrate.





The timeout time for read/write connections is set here. Cookie persistence is also set. The CookieJar has two callback interfaces. Use a HashMap to store cookies in saveFromResponse. LoadForRequest when needed. This allows you to carry cookies with every request.





This is the focus of this article on caching.

1. Obtain a File instance. This folder is specially used to store cached files.

2. To instantiate a Cache object, the first argument is the previous File instance, and the second argument is the maximum Cache size of the folder.

3. Add interceptors. Okhttp’s interceptors are a good thing. It is needed either by adding headers or by httploggingtor interceptor for logging data, or by adding caches. The first thing we need to do is define a strategy for caching. While the network is available, we successfully retrieve the data and cache it locally. When there is no network, we take out the cached data locally and load it. This completes the caching of data. Cached code can be treated as fixed code. There’s a lot of caching strategies for CacheControl on the web. I won’t repeat it here.

3. Precautions

Permissions, especially above 6.0 need to apply dynamically. Be careful when granting permissions.

Also, OkHttp’s cache can only be used for Get requests. OkHttp’s Cache class returns NULL for requests other than GET. Requests other than Get are not allowed, and post requests are technically allowed. But its complexity is high and its practicality is low.




Conclusion:

Finally, add a Demo address:

https://github.com/13046434521/CacheDemo

What is not clear about the specific code can be viewed here. Thank you very much. For that, thank you! If you like, you can point wave attention! Waiting for you here in rain and wind. Haha, thanks!