前言
Retrofit 从 2.6.0 版本开始, 内置了对 Kotlin Coroutines 的支持. 我们统一处理异常及响应状态码, 使用DSL 让代码更加漂亮整洁
先导包:
//协程
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
// Retrofit
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.2.0"
一、准备工作
1.BaseResp
统一的返回实体, 包含 code, msg, data; 这种服务器响应结构比较常见
data class BaseResp<T>(
// 响应状态码
var code: Int = -1,
// 响应信息
var msg: String = "",
// 数据实体
var data: T? = null
)
2.Api
这里是一个验证码请求接口, 使用的 Json 提交参数
interface Api {
@POST("api/getCode")
suspend fun getCode(@Body body: RequestBody): BaseResp<JsonObject?>
}
3.ApiManager
使用 枚举单例模式; 包括 初始化 Retrofit, OkHttpClient, 添加请求Token, 请求日志打印.
/**
* Retrofit 管理类;
*/
enum class ApiManager {
INSTANCE;
private val retrofit: Retrofit
val mApi: Api
private val mMediaTypeJson: MediaType?
init {
retrofit = Retrofit.Builder()
.baseUrl("https://... 服务器地址")
.client(initOkhttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
mApi = retrofit.create(Api::class.java)
mMediaTypeJson = "application/json; charset=utf-8".toMediaTypeOrNull()
}
private fun initOkhttpClient(): OkHttpClient {
return OkHttpClient.Build

本文介绍了如何在Kotlin中利用Retrofit 2.6.0及以上版本结合Coroutines进行网络请求,通过创建DSL和扩展函数实现优雅的错误处理和响应代码。首先,展示了基本的Retrofit配置,包括设置协程支持、统一的响应实体和API接口。接着,通过RetrofitDSL类和协程扩展函数封装了请求过程,简化了在Activity和ViewModel中的使用。这种方式使得代码更简洁,异常处理更直观。
最低0.47元/天 解锁文章
650

被折叠的 条评论
为什么被折叠?



