Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrofit 2.0b2 : How to get InputStream from the response?

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 ?

like image 582
CatFly Avatar asked Oct 09 '15 04:10

CatFly


People also ask

How do I make HTTP requests in Retrofit 2?

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.

What is onresponse and onfailure in Retrofit 2?

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.

Can retrofit 2 handle different server responses?

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?

What is retrofit2 callback in enqueue?

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)


Video Answer


1 Answers

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.

like image 76
iagreen Avatar answered Oct 18 '22 13:10

iagreen