package com.dayu.general.net
|
|
import com.dayu.baselibrary.BuildConfig
|
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// 包含header、body数据
|
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
|
//设置连接和读取时间
|
//添加统一的header
|
//添加日志拦截器
|
//添加数据请求统一处理拦截器
|
() {
|
|
|
|
private var retrofit: Retrofit? = null
|
val READ_TIME_OUT: Int = 10
|
val CONNECT_TIME_OUT: Int = 10
|
|
|
init {
|
val loggingInterceptor = HttpLoggingInterceptor()
|
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
|
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)
|
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
|
}
|
}
|
}
|