左晓为主开发手持机充值管理机
zuoxiao
2025-03-06 2e139af1d444c02efe248660174409abd2b713db
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
package com.dayu.general.net
 
import com.dayu.baselibrary.BuildConfig
import com.dayu.qiheonlinelibrary.net.MyIntercepterApplication
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
 
/**
 * Description:
 * Author: zuo
 * Date: 2025-03-06
 */
class RetrofitClient {
 
 
 
    private var retrofit: Retrofit? = null
    val READ_TIME_OUT: Int = 10
    val CONNECT_TIME_OUT: Int = 10
 
    private fun RetrofitClient() {
        val loggingInterceptor = HttpLoggingInterceptor()
        // 包含header、body数据
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        //        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        val builder:  OkHttpClient.Builder = OkHttpClient().newBuilder()
        //设置连接和读取时间
        builder.readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)
        builder.connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
        builder.writeTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
        //添加统一的header
        builder.addInterceptor(MyIntercepterApplication())
        //添加日志拦截器
        //添加数据请求统一处理拦截器
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(loggingInterceptor)
        }
 
        val client: OkHttpClient = builder.build()
 
        retrofit = Retrofit.Builder()
            .baseUrl(NetConstans.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .client(client).build()
    }
 
    @Synchronized
 
 
    fun getApiService(): ApiService {
        return retrofit?.create(ApiService::class.java) ?:  throw IllegalStateException("Retrofit instance is not initialized")
    }
 
    companion object{
        var mInstance: RetrofitClient? = null
        fun getInstance(): RetrofitClient {
            if (mInstance == null) {
                mInstance = RetrofitClient()
            }
            return mInstance as RetrofitClient
        }
    }
}