I have simple snippet code as below:
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
//
All that I want to know is, can I call safely .body()
on response
in try
body?
I've tried to preview my method information .getSub()
by calling CTRL-Q
in Android Studio but I got the only line
Inferred annotations: @org.jetbrains.annotations.NotNull
I believe it should be enough to convince me about that but I had to ask and be 100% sure.
如果响应不成功,则它可以为null。
It might be null, even when request is successful, as described on w3c:
"Response data Additional information may follow, in the format of a MIME message body. The significance of the data depends on the status code.
The Content-Type used for the data may be any Content-Type which the client has expressed its ability to accept, or text/plain, or text/html. That is, one can always assume that the client can handle text/plain and text/html."
reference: https://www.w3.org/Protocols/HTTP/Response.html
In Retrofit, the body method is defined as Nullable
@Nullable public T body() The deserialized response body of a successful response.
https://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.