OKHTTP adds interceptor and cache

Interceptors are divided into:
application interceptor (addInterceptor)
is mainly used to view request information and return information, such as link address, header information, parameter information, etc.
Network interceptor (addNetworkInterceptor)
can add, delete or replace request header information, and can also change The entity carried by the request

Caching literally means caching... With caching, your app can display previously cached data normally even when there is no network . If the data does not need to be changed for a long time, using caching can improve efficiency and reduce interaction with the server generated traffic.

Question and answer theater:

Question: I added a cache, why can't I read the cache when there is no network, or it still prompts a network problem

Answer: The cache requires certain fields (Cache-Control). If you have added the cache normally and already have a cache file locally, it means that these fields are missing

Solution:
1. Let the server add this field
2. Write an interceptor to add this field

Actual operation:
Adding caches and interceptors is in OkHttpClient.Builder(), as follows:
insert image description here

OkHttpClient client = new OkHttpClient.Builder()
       .connectTimeout(10, TimeUnit.SECONDS) //连接超时阈值
       .writeTimeout(10, TimeUnit.SECONDS) //写超时阈值
       .readTimeout(10, TimeUnit.SECONDS)  //读超时阈值
       .retryOnConnectionFailure(true) //当失败后重试
       .addNetworkInterceptor(new CacheInterceptor())//添加网络拦截器-设置缓存
       .addInterceptor(new LoggingInterceptor())//添加应用拦截器-日志拦截器
       .cache(new Cache(new File(this.getExternalCacheDir(), "okhttpcache"), 10 * 1024 * 1024))//添加缓存
       .build();
 Request request = new Request.Builder().url("https://www.wanandroid.com//hotkey/json").build();

The open API test of playing Android is used here, the request method is not written, and the request is made once. At this time, add the cache in the phone memory, open the phone space Android - data -
your APP package name - cache - okhttpcache,
you will find There are three files in it. At this time, it means that the cache has been successful. There is a file with suffixes of 0 and 1. It cannot be opened normally. After you change it to .txt, you will find that it is the data content that should be returned.

CacheInterceptor

class CacheInterceptor implements Interceptor {
    
    

        @Override
        public Response intercept(Chain chain) throws IOException {
    
    

            Response originResponse = chain.proceed(chain.request());

            //设置缓存时间为60秒,并移除了pragma消息头,移除它的原因是因为pragma也是控制缓存的一个消息头属性
            return originResponse.newBuilder().removeHeader("pragma")
                    .header("Cache-Control","max-age=600").build();
        }
    }

LoggingInterceptor

    public class LoggingInterceptor implements Interceptor {
    
    
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
    
    
            //这个chain里面包含了request和response,所以你要什么都可以从这里拿
            Request request = chain.request();

            long t1 = System.nanoTime();//请求发起的时间
            Log.i("dt",String.format("发送请求 %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);


            long t2 = System.nanoTime();//收到响应的时间

            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
            //个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);

            Log.i("dt",String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
                    response.request().url(),
                    responseBody.string(),
                    (t2 - t1) / 1e6d,
                    response.headers()));

            return response;
        }
    }

The interceptors are basically written in the same way, depending on how you add them to OKHTTP.

The above is adding the cache through the network interceptor and adding the request log by the application interceptor.

Thanks to these two articles for letting me know about interceptors and caching
android OkHttp Interceptor (Interceptor) to
clean up the caching problem in OkHttp

Guess you like

Origin blog.csdn.net/As_thin/article/details/124248663