.build()
fun create(serviceClass: Class): T = getRetrofit().create(serviceClass)
inline fun create(): T = create(T::class.java)
}
这里的代码就很简单了,通过网络地址构建一个Retrofit,然后根据传入的Service去访问接口,这里还有一个内联函数。
下面我们来构建这个服务接口,在此之前先在com.llw.goodnews包下新建一个utils包,包下新建一个Constant的类,里面的代码如下:
object Constant {
/**
- 天行数据Key,请使用自己的Key
*/
const val API_KEY = “d8bc937c366fcd1629e00f19105db258”
/**
- 请求接口成功状态码
*/
const val CODE = 200
/**
- 请求接口成功状态描述
*/
const val SUCCESS = “success”
}
这里就是一个常量类,我们在请求API接口时会用到的一些不变的值就放这里。然后我们在network包下新建一个ApiService接口,代码如下:
interface ApiService {
/**
- 获取新闻数据
*/
@GET(“/ncov/index?key=$API_KEY”)
fun getEpidemicNews(): Call
}
下面我们在network包下新建一个发起请求的NetworkRequest类,代码如下:
object NetworkRequest {
/**
- 创建服务
*/
private val service = ServiceCreator.create(ApiService::class.java)
//通过await()函数将getNews()函数也声明成挂起函数。使用协程
suspend fun getEpidemicNews() = service.getEpidemicNews().await()
/**
- Retrofit网络返回处理
*/
private suspend fun Call.await(): T = suspendCoroutine {
enqueue(object : Callback {
//正常返回
override fun onResponse(call: Call, response: Response) {
val body = response.body()
if (body != null) it.resume(body)
else it.resumeWithException(RuntimeException(“response body is null”))
}
//异常返回
override fun onFailure(call: Call, t: Throwable) {
it.resumeWithException(t)
}
})
}
}
这段代码解释一下:首先我们使用ServiceCreator创建了一个ApiService接口的动态代理对象,然后定义了一个getEpidemicNews函数,调用刚刚在ApiService中定义的getEpidem