封装retrofit网络请求工具类

/**
 * 封装retrofit网络请求工具类
 */
class RetrofitManager private constructor(url: String) {
    private val retrofit: Retrofit = Retrofit.Builder()
            .baseUrl(url)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().serializeNulls().create()))
            .build()

    private val apiService: ApiService by lazy { retrofit.create(ApiService::class.java) }

    companion object {
        private var INSTANCE: RetrofitManager? = null

        fun getInstance(url: String): RetrofitManager = INSTANCE ?: synchronized(this) {
            INSTANCE ?: RetrofitManager(url)
        }

        private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
                .addInterceptor(HttpLoggingInterceptor { msg -> msg.logi() }.setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build()
    }

    fun createApiService(isCheckConn: Boolean): ApiService? {
        return if (isCheckConn) {
            if (isConnected()) {
                apiService
            } else {
                toastShort(R.string.error_network)
                null
            }
        } else {
            apiService
        }
    }
}

你可能感兴趣的:(java,Kotlin)