【发布时间】:2023-03-14 11:46:02
【问题描述】:
我正在测试 Retrofit 以将其与 Volley 进行比较,我正在努力从我的请求中获得响应。例如,我做这样的事情:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://localhost:8080")
.build();
MyService service = restAdapter.create(MyService.class);
service.getToto("toto", new Callback<Toto>() {
@Override
public void success(Toto toto, Response response) {
// Try to get response body
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(
new InputStreamReader(response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
}
@Override
public void failure(RetrofitError error) {}
});
有效,对象toto已设置,但出于测试目的,我还想显示服务器返回的JSON响应。
所以我试图从response.getBody() 读取InputStream,这是一个TypedInputStream。
不幸的是,我总是收到IOException : Stream is closed。
我尝试使用 Retrofit 中的 Utils 类,但得到相同的 IOException 错误。
【问题讨论】:
-
我认为您可以使用自定义转换器将解析委托给真正的转换器并记录服务器的响应More info here
-
我也有同样的问题。同样简单的设置,我的实际自定义响应对象很好,填充了等等,但是当我尝试直接从响应中获取输入流时,同样的错误。但
failure()中的响应输入流工作正常 -
实际上只是注意到了一些奇怪的事情。当我打开登录改造时,它会吐出我想看到的所有信息,我的输入流消耗工作正常,没有抛出错误。奇怪...
-
@trippedout 请看下面我的回答...
-
您可以使用
JsonObject作为响应,然后从josnObject.toString()获取您的String