Linjiajia
2023-03-17 85e989454fcc64a3cd99eaf659e00c4a2c10b534
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
package com.android.app_base.http;
 
import androidx.collection.CircularArray;
 
import java.util.HashMap;
import java.util.Map;
 
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
 
/**
 * @author Ljj
 * @date 2023.03.02. 14:11
 * @desc Retrofit管理,可以有不同的 baseUrl
 */
public class RetrofitManager {
 
    private static volatile RetrofitManager instance;
    private final Map<String,Retrofit> retrofitMap;
    private OkHttpClient mClient;
 
    public static RetrofitManager getInstance(){
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }
 
    private RetrofitManager(){
        retrofitMap = new HashMap<>();
        mClient = OkHttpHelper.getOkHttpClient();
    }
 
    /**
     * 获取Retrofit对象
     */
    public Retrofit getRetrofit(String baseUrl) {
        Retrofit retrofit = retrofitMap.get(baseUrl);
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(mClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .baseUrl(baseUrl)
                    .build();
            retrofitMap.put(baseUrl, retrofit);
        }
        return retrofit;
    }
 
    /**
     * 设置 自定义OkHttpClient
     */
    public RetrofitManager setOkHttpClient(OkHttpClient client) {
        this.mClient = client;
        return instance;
    }
 
 
}