Linjiajia
2023-04-24 fcdddf8b9b34f9930bec454b5fffe41c0e33ba3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.android.app_base.http;
 
import android.content.Context;
 
import androidx.annotation.NonNull;
 
import com.android.app_base.BuildConfig;
import com.android.app_base.base.BaseApplication;
import com.android.app_base.http.interceptor.AuthInterceptor;
import com.android.app_base.http.interceptor.CacheInterceptor;
import com.android.app_base.http.interceptor.LogInterceptor;
import com.blankj.utilcode.util.LogUtils;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
 
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;
 
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
 
/**
 * @author Ljj
 * @date 2023.03.01. 22:36
 * @desc 网络请求OkHttp配置
 */
public class OkHttpHelper {
    //超时时间
    private final static int READ_TIMEOUT = 15;
    private final static int CONNECT_TIMEOUT = 15;
    private final static int WRITE_TIMEOUT = 15;
    //缓存时间
    private final static int CACHE_SIZE = 10 * 1024 * 1024;
    private static volatile OkHttpClient okHttpClient;
 
    private OkHttpHelper() {
 
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        //读取超时
        clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
        //连接超时
        clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        //写入超时
        clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        //错误重连
        clientBuilder.retryOnConnectionFailure(true);
        //cookie
        Context mContext = BaseApplication.getInstance();
        clientBuilder.cookieJar(new PersistentCookieJar(new SetCookieCache(),new SharedPrefsCookiePersistor(mContext)));
 
        //缓存拦截
        Cache cache = new Cache(new File(mContext.getCacheDir(),"http_cache"),CACHE_SIZE);
        clientBuilder.cache(cache).addInterceptor(new CacheInterceptor());
 
        //增加头部信息拦截
        clientBuilder.addInterceptor(new Interceptor() {
            @NonNull
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request build = chain.request().newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .build();
                return chain.proceed(build);
            }
        });
        clientBuilder.addInterceptor(new LogInterceptor());//拦截器添加公共参数
        clientBuilder.addInterceptor(new AuthInterceptor());//拦截器token失效处理
        //log日志拦截
        if (BuildConfig.DEBUG) {
            clientBuilder.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    try {
                        String msg = message.replaceAll("%(?![0-9a-fA-F]{2})","%25");
                        String text = URLDecoder.decode(msg, "utf-8");
                        LogUtils.dTag("LOG","网络请求"+text);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        LogUtils.dTag("LOG","网络请求错误信息"+e.getMessage());
                    }
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        okHttpClient = clientBuilder.build();
    }
 
 
    public static OkHttpClient getOkHttpClient() {
        if (null == okHttpClient) {
            synchronized (OkHttpHelper.class) {
                if (okHttpClient == null) {
                    new OkHttpHelper();
                    return okHttpClient;
                }
            }
        }
        return okHttpClient;
    }
 
    public static void addInterceptor(Interceptor interceptor){
        okHttpClient = getOkHttpClient().newBuilder().addInterceptor(interceptor).build();
    }
}