alla alla - 1 year ago 99
Android Question

Cannot convert Retrofit Response to error custom object twice

Why I cannot convert Retrofit Response to object of this class twice:

public static class ApiError { //inner class in REST-class
private int errorCode;
private String message;

public int errorCode() {
return errorCode;

public String message() {
return message;


public static ApiError parseError(Response<?> response) {
Converter<ResponseBody, ApiError> converter =
retrofit.responseBodyConverter(ApiError.class, new Annotation[0]);

ApiError error;

try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new ApiError();

return error;

object has nothing in their fields
But why?

REST.ApiError error = REST.parseError(response);
REST.ApiError error2 = REST.parseError(response);

I see nothing about this in docs.

Answer Source

When you call response.errorBody() you obtain ResponseBody instance, which definition is:

public abstract class ResponseBody implements Closeable

That means, that when you try to read the stream (probably by using public final byte[] bytes() method), you flush the stream. It is closed therefore cannot be read second time.


Obtain instance of Reader from ResponseBody and wrap it into BufferedStream:

BufferedReader streams = new BufferedReader(response.errorBody().charStream());

Then you might call reset() on the sream as many often as you like:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download