[英]How to get both a POJO and the raw response string back with retrofit?
FATAL EXCEPTION: main Process: com.packagename, PID: 11371 java.lang.IllegalStateException: Cannot read raw response body of a converted body.
In retrofit, you can only ever read response.body() once, since it's a stream and it automatically closes once you call .string()
or when it auto-converts to whatever model class you have in Response<T>
return type.在改造中,您只能读取 response.body() 一次,因为它是一个流,一旦您调用
.string()
或当它自动转换为您在Response<T>
返回类型中拥有的任何模型类时,它就会自动关闭。 If you try to read twice, then you get the above error.如果您尝试阅读两次,则会出现上述错误。
I need both the raw response string as well as the model class .我需要原始响应字符串以及模型类。 What's the best way to do this?
做到这一点的最佳方法是什么? I do not want to make the API call twice.
我不想两次调用 API。 Is there some way to duplicate the response body?
有没有办法复制响应体? Ideally, I'd like to simply get String and T back with the response.
理想情况下,我想简单地将 String 和 T 带回响应。 That is, to not have to give up the generic type converter goodies that come with retrofit
也就是说,不必放弃改造带来的通用类型转换器
You could get the raw response body by adding an interceptor ( https://square.github.io/okhttp/interceptors/ ) and copying the responsebody BufferedSource before returning the response.您可以通过添加拦截器( https://square.github.io/okhttp/interceptors/ )并在返回响应之前复制响应主体 BufferedSource 来获取原始响应主体。 I'm having trouble seeing why someone would want to do this though.
我无法理解为什么有人想要这样做。
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
ByteArrayOutputStream output = new ByteArrayOutputStream();
responseBody.source().getBuffer().copyTo(output);
String rawResponseBody = output.toString();
return response;
example for model class:模型类示例:
public class Post {
@SerializedName("text")
private String text;
private User user;
public String getText() {
return text;
}
public User getUser() {
return user;
}
}
class User{
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
}}
for better answer: put your model class and onResponse method body in your question为了获得更好的答案:将您的模型类和 onResponse 方法主体放在您的问题中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.