Rai*_*ker 2 android retrofit retrofit2 kotlin-coroutines
我有一个改造服务:
suspend fun getArticles(): Articles
Run Code Online (Sandbox Code Playgroud)
通常我可以try/catch在出现错误的情况下获得响应代码。
try {
val articles = service.getArticles()
} catch (e: Exception) {
// I can get only codes different from 200...
}
Run Code Online (Sandbox Code Playgroud)
但是如果我需要区分 200 和 202 代码并且我的服务只返回数据对象怎么办?
如果响应成功,如何获取响应代码?
你的界面看起来像这样
suspend fun getArticles(): Response<Articles>
Run Code Online (Sandbox Code Playgroud)
然后你像这样使用
val response = service.getArticles()
response.code() //gives you response code
val articles = response.body
Run Code Online (Sandbox Code Playgroud)
或更简单的解决方案是
if (response.isSuccessful){ // Successful is any code between the range [200..300)
val articles = response.body
}
Run Code Online (Sandbox Code Playgroud)