改造2.0b2:如何从响应中获取InputStream? [英] retrofit 2.0b2 : How to get InputStream from the response?

查看:727
本文介绍了改造2.0b2:如何从响应中获取InputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Retrofit 2.0b2。得到回复后,我尝试通过以下方式从响应中获取InputStream:

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 ?

推荐答案

如果你想要原始流,请告诉retrofit返回一个OkHttp ResponseBody

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.

由于响应正文由有限的资源支持,因此必须在使用后关闭 responseBody 对象。因此,上面的代码使用 try-with-resources 语句。

这篇关于改造2.0b2:如何从响应中获取InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆