alla alla - 1 month ago 13
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
@SerializedName("error_code")
private int errorCode;
@SerializedName("error_description")
private String message;

public int errorCode() {
return errorCode;
}

public String message() {
return message;
}
}


Convertion:

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;
}


So
error2
object has nothing in their fields
errorCode
and
message
But why?

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


I see nothing about this in docs.

Answer

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.

Solution:

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:

streams.reset();