admin
2024-07-03 a40e0e51331e5e6f69e8bed5940512b29150c7a9
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
112
113
114
115
116
package com.taoke.autopay.android.data.network;
 
import com.google.gson.GsonBuilder;
import com.taoke.autopay.android.App;
import com.taoke.autopay.android.utils.MD5Utils;
import com.taoke.autopay.android.utils.StorageUtils;
import com.taoke.autopay.android.BuildConfig;
 
import java.io.File;
import java.util.concurrent.TimeUnit;
 
import okhttp3.Cache;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import timber.log.Timber;
 
public class RestAPI {
 
    private static final String API_URL = BuildConfig.API_URL;
 
    private static final int DISK_CACHE_SIZE = 20 * 1024 * 1024; // 20MB
 
    private Retrofit retrofit;
 
    private ApiService apiService;
 
    private static final class Holder {
        private static final RestAPI INSTANCE = new RestAPI();
    }
 
    public static RestAPI getInstance() {
        return Holder.INSTANCE;
    }
 
    private Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = createRetrofit(API_URL);
        }
        return retrofit;
    }
 
    private Retrofit createRetrofit(String baseUrl) {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .cache(getCache());
        clientBuilder
                .addInterceptor(chain -> {
                    Request request = chain.request();
                    RequestBody body = request.body();
                    String sign = "";
                    if (request.method().equalsIgnoreCase("POST") && body instanceof FormBody) {
                        FormBody formBody = (FormBody) body;
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < formBody.size(); i++) {
                            String name = formBody.name(i);
                            String value = formBody.value(i);
                            sb.append(name).append("=").append(value).append("&");
                        }
                        sb.append("KEY");
                        sign = MD5Utils.getMD532(sb.toString());
                    }
                    return chain.proceed(chain.request()
                            .newBuilder()
                            .header("timestamp", String.valueOf(System.currentTimeMillis()))
                            .header("version", "1.0.0")
                            .header("packages", "com.taoke.autopay.android")
                            .header("sign", sign)
                            .build());
                });
        if (BuildConfig.DEBUG) {
            clientBuilder.interceptors().add(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()))
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .client(clientBuilder.build())
                .build();
    }
 
    private static int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }
 
    private static Cache getCache() {
        Cache cache = null;
        // Install an HTTP cache in the application cache directory.
        try {
            File cacheDir = new File(StorageUtils.getCacheDirectory(App.getInstance()), "http");
            cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        } catch (Exception e) {
            Timber.e(e, "Unable to install disk cache.");
        }
        return cache;
    }
 
    public ApiService apiService() {
        if (apiService == null) {
            apiService = getRetrofit().create(ApiService.class);
        }
        return apiService;
    }
}