Android-使用改造和协程获取响应状态代码

我有一个改造服务:

suspend fun getArticles(): Articles

通常我可以try/catch在出现错误的情况下获得响应代码。

try {
    val articles = service.getArticles()
} catch (e: Exception) {
    // I can get only codes different from 200...
}

但是如果我需要区分 200 和 202 代码并且我的服务只返回数据对象怎么办?

如果响应成功,如何获取响应代码?

回答

你的界面看起来像这样

suspend fun getArticles(): Response<Articles>

然后你像这样使用

val response = service.getArticles()
response.code() //gives you response code
val articles = response.body

或更简单的解决方案是

if (response.isSuccessful){ // Successful is any code between the range [200..300)
    val articles = response.body
}


以上是Android-使用改造和协程获取响应状态代码的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>