I'm using Retrofit 2.0b2. After getting a response, I tried getting an InputStream from the response by :
Response<JsonNode> response = call.execute();
InputStream is = response.raw().body().byteStream();
but the app keep throwing :
java.lang.IllegalStateException: Cannot read raw response body of a converted body.
at retrofit.OkHttpCall$NoContentResponseBody.source(OkHttpCall.java:184)
at com.squareup.okhttp.ResponseBody.byteStream(ResponseBody.java:43)
at ...
Despite the response returned correctly. What am I doing wrong here ?
In Retrofit 2, all requests are wrapped into a retrofit2.Call object. Each call yields its own HTTP request and response pair. Call interface provides two methods for making the HTTP requests: execute () – Synchronously send the request and return its response.
Usually, when using Retrofit 2, we have two callback listeners: onResponse and onFailure If onResponse is called, it doesn't always mean that we get the success condition. Usually a response is considered success if the status scode is 2xx and Retrofit has already provides isSuccessful () method.
After trying out Retrofit 2, I have adjusted the previous sample and managed to achieve the same results (with some improvements ). In order to test your Android apps, one thing that normally gets frequently overlooked is the apps ability to handle different server responses. What if your server goes down for a while?
enqueue (retrofit2.Callback) – Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response. 2. Retrofit Call Examples 2.1. Synchronous Call Example ( Not recommended)
If you want the raw stream, tell retrofit to return an OkHttp ResponseBody
.
import okhttp3.ResponseBody;
import retrofit2.Response;
Response<ResponseBody> response = call.execute();
try ( ResponseBody responseBody = response.body() ) {
InputStream is = responseBody.byteStream();
// ...
}
Remember to update your interface, too.
As the response body is backed by a limited resource, the responseBody
object must be closed after usage. Therefore above code uses a try-with-resources statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With