Android - 使用改造和协程获取响应状态代码
Android - get response status code using retrofit and coroutines
我有改装服务:
suspend fun getArticles(): Articles
通常我可以在 try/catch
中得到响应代码以防出错。
try {
val articles = service.getArticles()
} catch (e: Exception) {
// I can get only codes different from 200...
}
但是,如果我需要区分 200 和 202 代码以及我的服务 returns 我只有数据对象怎么办?
回复成功如何获取回复码?
你的界面应该是这样的
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
}
我有改装服务:
suspend fun getArticles(): Articles
通常我可以在 try/catch
中得到响应代码以防出错。
try {
val articles = service.getArticles()
} catch (e: Exception) {
// I can get only codes different from 200...
}
但是,如果我需要区分 200 和 202 代码以及我的服务 returns 我只有数据对象怎么办?
回复成功如何获取回复码?
你的界面应该是这样的
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
}