Retrofit是非常强大的网络请求方案,虽然官方也有adapter-rxjava2
库,但是我觉得并不好用,其实通过Kotlin的拓展属性即可实现非常好用的方案。
REST API
每个工程师定义的REST API都不太一样,但是基本的思路都是一样。
- 如果没有出现异常就是返回对象或者返回空对象;
- 如果请求出现错误,HTTP的statusCode是大于400,只有请求正常才是2xx。
- 如果请求出错,那么errorBody就会返回 错误码及错误信息。
{
"error_code":1101,
"error":"验证码错误"
}
添加依赖
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
}
创建NetworkException.kt
class NetworkException : Exception() {
var error_code: String = ""
var error: String? = ""
override val message: String?
get() = error
}
创建文件_Ca