【问题标题】:Android - get response status code using retrofit and coroutinesAndroid - 使用改造和协程获取响应状态代码
【发布时间】:2021-07-11 16:51:02
【问题描述】:

我有改造服务:

suspend fun getArticles(): Articles

如果出现错误,通常我可以在try/catch 中获得响应代码。

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

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

响应成功后如何获取响应码?

【问题讨论】:

    标签: android retrofit retrofit2 kotlin-coroutines


    【解决方案1】:

    你的界面应该是这样的

    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
    }
    

    【讨论】:

    • 但如果我不使用 Response 只有文章?
    • @Fortran 你需要使用Response&lt;Articles&gt; 才能知道
    猜你喜欢
    • 1970-01-01
    • 2015-10-26
    • 2020-09-07
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2019-07-20
    • 2014-10-17
    • 2020-01-10
    相关资源
    最近更新 更多