前言
上一篇关于MVVM 架构的基类封装,这篇会在MVVM 的基础上示范使用 kotlin+retrofit+okhttp 封装的网络框架,里面会涉及到协程的使用,
协程异常处理包装。
导入相关包
kotlin 相关配置见上一篇,这里主要是Retrofit 和okHttp3 的包
api 'com.squareup.okhttp3:logging-interceptor:3.6.0'
api 'com.squareup.retrofit2:adapter-rxjava2:2.6.0'
api 'com.squareup.retrofit2:adapter-rxjava:2.6.0'
api 'com.squareup.okhttp3:okhttp:3.12.0'
api 'com.squareup.retrofit2:retrofit:2.6.0'
api 'com.squareup.retrofit2:converter-gson:2.6.0'
api 'com.squareup.retrofit2:adapter-rxjava2:2.6.0'
封装
先看看图中基本的结构

- RetrofitClient: client 管理类
这里是整个业务封装的核心,其中包括https 证书校验、baseUrl 切换
class RetrofitClient {
/**
* retrofit 初始化build
*/
private fun RetrofitClient() {
}
//做成单例
companion object {
private var retrofitClient: RetrofitClient? = null
private const val DEFAULT_TIME_OUT = 15
private val sRetrofitManager: MutableMap<Int, Retrofit> = HashMap()
fun getInstance(): RetrofitClient {
if (retrofitClient == null) {
synchronized(RetrofitClient::class.java) {
retrofitClient = RetrofitClient()
return retrofitClient as RetrofitClient
}
}
return retrofitClient as RetrofitClient
}
}
/**
* 创建连接客户端
*/
private fun createOkHttpClient(): OkHttpClient {
//设置请求头拦截器
//设置日志拦截器
val httpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
//根据需求添加不同的拦截器
return OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
.connectionPool(ConnectionPool(8, 10, TimeUnit.SECONDS)) //添加这两行代码
.sslSocketFactory(TrustAllCerts.createSSLSocketFactory()!!, TrustAllCerts())
.hostnameVerifier(TrustAllCerts.TrustAllHostnameVerifier())
.addInterceptor(httpLoggingInterceptor)
.build()
}
/**
* 根据host 类型判断是否需要重新创建Client,因为一个app 有不同的BaseUrl,切换BaseUrl 就需要重新创建Client
* 所以,就根据类型来从map中取出对应的client
*/
fun <T> getDefault(interfaceServer: Class<T>?, hostType: Int): T {
val retrofitManager = sRetrofitManager[hostType]
return if (retrofitManager == null) {
create(interfaceServer, hostType)
} else retrofitManager.create(interfaceServer!!)
}
/**
*
*/
private fun <T> create(interfaceServer: Class<T>?

本文介绍了如何使用Kotlin、Retrofit和OkHttp封装网络框架,涉及协程、异常处理及MVVM架构。通过单例管理RetrofitClient,实现BaseUrl的动态切换,并提供了网络请求的基类封装,简化了 ViewModel 中的网络调用。同时展示了在协程中如何发起网络请求,避免手动处理线程。整个封装旨在提高代码的可维护性和简洁性。
最低0.47元/天 解锁文章
2052





