我正在使用Retrofit 2.0b2。得到回复后,我尝试通过以下方式从响应中获取InputStream:
Response<JsonNode> response = call.execute();
InputStream is = response.raw().body().byteStream();
但应用程序不断抛出:
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 ...
尽管响应正确返回。我在这里做错了什么?
答案 0 :(得分:20)
如果你想要原始流,请告诉改造返回OkHttp ResponseBody
。
import okhttp3.ResponseBody;
import retrofit2.Response;
Response<ResponseBody> response = call.execute();
try ( ResponseBody responseBody = response.body() ) {
InputStream is = responseBody.byteStream();
// ...
}
请记住也要更新您的界面。
As the response body is backed by a limited resource, the responseBody
object must be closed after usage。因此,上面的代码使用 try-with-resources 语句。