Access the raw response body in a Retrofit callback

Retrofit version: 2.1.0
OkHttp version: 3.4.1

In the method of onResponsemy modification Callback, 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 BaseResponseBodyis my own type (not related to OkHttp ResponseBody) that wraps the generic type T extends Validatable, where Validatableis the interface that provides the method isValidused to confirm that deserialized answers satisfy the given constraints.

If I get an answer that is supposedly successful (2XX HTTP code, nonzero response organ, etc.), but whose deserialized body does not pass this verification step (i.e. containsValidSuccessreturns false), I would like to enter a dialog, a message which contains the body of the raw (pre-deserialization) response. However, it seems that I cannot access this raw body of the response using the Retrofit method Response.

I read other pages that seem to suggest that Interceptormay be better suited to my needs. I am familiar with interceptors and use them for other call manipulations in my application, but I do not see exactly how to transfer information from my interceptor to the final method Callback.onResponseto represent the dialog.

? - API- Retrofit? ? !

+4
1

@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.
 }
}

POJO,

Gson g= new Gson(); 
POJOClass pojo=g.fromJson(response.body,POJOClass.class);
+1

Source: https://habr.com/ru/post/1659078/


All Articles