Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access raw response body in Retrofit callback

Retrofit version: 2.1.0
OkHttp version: 3.4.1

In the onResponse method of my Retrofit Callback implementation, I have the following logic:

@Override
public void onResponse(Call<BaseResponseBody<T>> call, Response<BaseResponseBody<T>> response) {
  if (response != null && response.isSuccessful() && response.body() != null && response.body().containsValidSuccess()) {
    // Perform actions using response.body().getValue().
  } else {
    // If containsValidSuccess returns false, show a dialog that includes the raw JSON response body.
  }
}

Here BaseResponseBody is my own type (not related to OkHttp's ResponseBody) that wraps a generic type T extends Validatable, where Validatable is an interface that exposes an isValid method used to confirm that deserialized responses satisfy given constraints.

If I receive a response that is ostensibly successful (HTTP code 2XX, non-null response body, etc.), but whose deserialized body does not pass this validation step (i.e. containsValidSuccess returns false), I would like to present a dialog whose message includes the raw (pre-deserialization) response body. However, I don't seem to be able to access this raw response body through the Retrofit Response type.

I have read other pages that seem to suggest an Interceptor might better suit my needs. I'm familiar with interceptors and use them for other call manipulations within my app, but I don't see exactly how I would pass information from my interceptor to the final Callback.onResponse method in order to present the dialog.

Am I on the right path? Am I missing something obvious in the Retrofit APIs? How can I achieve my stated goal? Thanks!

like image 550
stkent Avatar asked Oct 27 '16 15:10

stkent


1 Answers

try this

@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
 if (response != null && response.isSuccessful() && response.body() != null && response.body().containsValidSuccess()) {
   // Perform actions using response.body().getValue().
 } else {
  // If containsValidSuccess returns false, show a dialog that includes the raw JSON response body.
 }
}

after then you can put it to your POJO like this

Gson g= new Gson(); 
POJOClass pojo=g.fromJson(response.body,POJOClass.class);
like image 184
Vishal Sanghani Avatar answered Oct 17 '22 04:10

Vishal Sanghani