繁体   English   中英

在try body中从Response Retrofit调用.body()是否会返回null?

[英]Does calling .body() from response Retrofit in try body might returns null?

我有以下简单的代码段:

Sub sub = null;

try {
    Response<Sub> response = MyRestApi.getInstance().getSub().execute();
    sub = response.body(); // Does variable response is always non null?
} catch (IOException e) {
    e.printStackTrace();
}

//
// ... further operations on sub
// 

我只想知道,我可以在try body的response中安全地调用.body()吗?

我试图通过在Android Studio中调用CTRL-Q预览我的方法信息.getSub() ,但是我只有一行

Inferred annotations: @org.jetbrains.annotations.NotNull

我相信这足以说服我,但我必须提出要求并百分百确定。

如果响应不成功,则它可以为null。

如w3c所述,即使请求成功,它也可能为null:

“响应数据可能会以MIME消息正文的格式附加信息。数据的重要性取决于状态码。

用于数据的Content-Type可以是客户端已表达其接受能力的任何Content-Type,也可以是text / plain或text / html。 也就是说,人们总是可以假设客户端可以处理text / plain和text / html。”

参考: https : //www.w3.org/Protocols/HTTP/Response.html

在翻新中,body方法定义为Nullable

@Nullable public T body()成功响应的反序列化响应体。

https://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM