在Retrofit回调中访问原始响应正文 [英] Access raw response body in Retrofit callback

查看:74
本文介绍了在Retrofit回调中访问原始响应正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

改造版本:2.1.0
OkHttp版本:3.4.1

Retrofit version: 2.1.0
OkHttp version: 3.4.1

在我的Retrofit的onResponse方法中 Callback 实现,我有以下逻辑:

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

这里BaseResponseBody是我自己的类型(与OkHttp的 ResponseBody )包装通用类型T extends Validatable,其中Validatable是一个接口,该接口公开用于确认反序列化响应满足给定约束的isValid方法.

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.

如果我收到表面上成功的响应(HTTP代码2XX,非空响应主体等),但其反序列化主体未通过此验证步骤(即containsValidSuccess返回false),我想显示一个对话框,其消息包含原始(反序列化前)响应正文.但是,我似乎无法通过Retrofit Response 类型.

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.

我已经阅读了其他页面,这些页面似乎建议使用 可能更适合我的需求.我熟悉拦截器并将其用于应用程序中的其他调用操作,但是我没有确切地知道如何将信息从拦截器传递到最终的Callback.onResponse方法以显示对话框.

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.

我在正确的道路上吗?我是否在Retrofit API中缺少明显的东西?我如何实现既定目标?谢谢!

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

推荐答案

尝试一下

@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

after then you can put it to your POJO like this

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

这篇关于在Retrofit回调中访问原始响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆