简体   繁体   中英

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. 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. Is there some way to duplicate the response body? Ideally, I'd like to simply get String and T back with the response. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM