【问题标题】:Can Retrofit2 onResponse method have Null Response?Retrofit2 onResponse 方法可以有空响应吗?
【发布时间】:2017-07-27 07:09:38
【问题描述】:

我正在使用Retrofit 2.1.0 库,并使用call.enqueue 方法进行异步API 调用。

CallBack 类返回 onResponse(Call call, Response response)onFailure (Call call, Throwable t)

我的问题是,假设onResponse 方法中的 Response(不是 response.body)对象将始终为 NonNull 是否安全?

如果可以为null,可能的场景是什么?

我查看了网上和 Retrofit 文档,但没有明确的答案。

【问题讨论】:

  • 请求有错误可以为null。看下面的回答stackoverflow.com/questions/42527551/…
  • @ArpanSharma body()errorBody() 可以为空。关于Response参数的问题
  • 好的。不,不可能,答案是对的。

标签: android retrofit2


【解决方案1】:

它不应该为空。

您可以看到in Retrofit source code 只返回一个Response.successReponse.error

您可以使用Response.isSuccessful() 检查 HTTP 请求是否成功。

如果Response 可能为空,那么该方法将抛出NullPointerException

如果有空响应的场景,或者解析响应时抛出一些异常,那么onFailure would be entered

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多