[英]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.