Retrofit2 当状态代码 200 但 json 结构与数据模型类不同时处理条件

2022-09-03 01:48:44

我正在使用 Retrofit2 和 .RxJava2CallAdapterFactory

我使用的 API 始终返回状态代码为 200,对于成功和响应 JSON 字符串,JSON 结构完全不同。由于状态代码始终为 200,因此始终调用 onResponse() 方法。因此,我无法从错误条件中的JSON中提取错误消息。

解决方案 1:

我用于获取响应字符串并手动使用Gson来解析响应。如何在不使用GSON或任何其他库的情况下使用改造获得String响应,而无需在Android中使用GSON或任何其他库ScalarsConverterFactory

此解决方案的问题:我计划使用RxJava2CallAdapterFactory,因为改造方法应该返回DataModel类。

我需要找到这个问题的最佳解决方案,这样我就可以继续从改造方法返回数据模型类,并以某种方式从响应中识别错误条件(识别响应JSON与数据模型不匹配),然后将错误JSON解析为数据模型。

改造客户端

 public static Retrofit getClient(String url) {
        if (apiClient == null) {

            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();

            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
            apiClient = new Retrofit.Builder()
                    .baseUrl(url)
                    /*addCallAdapterFactory for RX Recyclerviews*/
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    /* add ScalarsConverterFactory to get json string as response */
//                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
//                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(httpClient)
                    .build();
        }
        return apiClient;
    }

方法

public static void getLoginAPIResponse(String username, String password, String sourceId, String uuid, final HttpCallback httpCallback) {
        baseUrl = AppPreference.getParam(UiUtils.getContext(), SPConstants.BASE_URL, "").toString();
        ApiInterface apiService =
                ApiClient.getClient(baseUrl).create(ApiInterface.class);

        Call<LoginBean> call = apiService.getLoginResponse(queryParams);
        call.enqueue(new Callback<LoginBean>() {

            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {

                if (response.body().isObjectNull()) {
                    httpCallback.resultCallback(APIConstants.API_LOGIN, HttpCallback.REQUEST_TYPE_GET,
                            HttpCallback.RETURN_TYPE_FAILURE, 0, null);
                    return;
                }
                httpCallback.resultCallback(APIConstants.API_LOGIN, HttpCallback.REQUEST_TYPE_GET,
                        HttpCallback.RETURN_TYPE_SUCCESS, response.code(), response.body());
            }





        @Override
        public void onFailure(Call<LoginBean> call, Throwable t) {
            // Log error here since request failed
            httpCallback.resultCallback(APIConstants.API_APP_VERIFICATION, HttpCallback.REQUEST_TYPE_GET,
                    HttpCallback.RETURN_TYPE_FAILURE, 0, t);
            t.printStackTrace();
        }
    });
}

接口

@GET("App/login")
Call<LoginBean> getLoginResponse(@QueryMap Map<String, String> queryMap);

PS :API目前无法更改,因为其他一些应用程序正在使用它。

  • Gson解析器不返回空对象实例,以便我了解json结构和数据模型不匹配。

  • RestAdapter 在 Retrofit 2 中被弃用

我正在寻找解决此问题的最佳方法,最好避免手动json解析,并充分利用改造和RX适配器。

编辑

响应代码 200

  1. response.isSuccessful() == true

  2. response.body() != null也是 true,因为 Gson 从不创建空实例,或者在 JSON 结构不匹配时引发任何异常

  3. response.errorBody() == null始终作为从服务器作为输入流发送的响应。

    if (response.isSuccessful() && response.body() != null) {
        //control always here as status code 200 for error condition also
    }else if(response.errorBody()!=null){
        //control never reaches here
    }
    

编辑 2

溶液

该解决方案基于anstaendig答案

  • 我创建了一个基泛型类来进一步回答这个问题。
  • 由于我有多个 API 和数据模型,因此我必须为每个 api 和数据模型创建反造器

碱性原料豆

public class BaseApiBean<T> {

    @Nullable
    private T responseBean;

    @Nullable
    private ErrorBean errorBean;

    public BaseApiBean(T responseBean, ErrorBean errorBean) {
        this.responseBean = responseBean;
        this.errorBean = errorBean;
    }

    public T getResponseBean() {
        return responseBean;
    }

    public void setResponseBean(T responseBean) {
        this.responseBean = responseBean;
    }

    public ErrorBean getErrorBean() {
        return errorBean;
    }

    public void setErrorBean(ErrorBean errorBean) {
        this.errorBean = errorBean;
    }
}

基础解串器

  public abstract class BaseDeserializer implements JsonDeserializer<BaseApiBean> {


        @Override
        public BaseApiBean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            // Get JsonObject
            final JsonObject jsonObject = json.getAsJsonObject();
            if (jsonObject.has("result")) {
                   /* {"result":"404"}*/
                ErrorBean errorMessage = new Gson().fromJson(jsonObject, ErrorBean.class);
                return getResponseBean(errorMessage);
            } else {

                return getResponseBean(jsonObject);
            }
        }

        public abstract BaseApiBean getResponseBean(ErrorBean errorBean);
        public abstract BaseApiBean getResponseBean(JsonObject jsonObject);
    }

每个 API 的自定义解串器

public class LoginDeserializer extends BaseDeserializer {


    @Override
    public BaseApiBean getResponseBean(ErrorBean errorBean) {
        return new LoginResponse(null, errorBean);
    }

    @Override
    public BaseApiBean getResponseBean(JsonObject jsonObject) {

        LoginBean loginBean = (new Gson().fromJson(jsonObject, LoginBean.class));
        return new LoginResponse(loginBean, null);
    }
}

自定义响应比恩

public class LoginResponse extends BaseApiBean<LoginBean> {
    public LoginResponse(LoginBean responseBean, ErrorBean errorBean) {
        super(responseBean, errorBean);
    }

}

客户

public class ApiClient {
    private static Retrofit apiClient = null;
    private static Retrofit apiClientForFeedBack = null;
    private static LoginDeserializer loginDeserializer = new LoginDeserializer();
    private static AppVerificationDeserializer appVerificationDeserializer = new AppVerificationDeserializer();


    public static Retrofit getClient(String url) {
        if (apiClient == null) {

            GsonBuilder gsonBuilder=new GsonBuilder();
            gsonBuilder.registerTypeAdapter(LoginResponse.class,
                    loginDeserializer);
            gsonBuilder.registerTypeAdapter(AppVerificationResponse.class,
                    appVerificationDeserializer);
            Gson gson= gsonBuilder.create();


            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();

            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(interceptor)
                    .retryOnConnectionFailure(true)
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .build();

            apiClient = new Retrofit.Builder()
                    .baseUrl(url)
                    /*addCallAdapterFactory for RX Recyclerviews*/
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    /* add ScalarsConverterFactory to get json string as response */
//                    .addConverterFactory(ScalarsConverterFactory.create())
//                    .addConverterFactory(GsonConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(httpClient)
                    .build();
        }
        return apiClient;
    }

处理响应

 public static void getLoginAPIResponse(String username, String password, String sourceId, String uuid, final HttpCallback httpCallback) {
        baseUrl = AppPreference.getParam(getContext(), SPConstants.MT4_BASE_URL, "").toString();
        ApiInterface apiService =
                ApiClient.getClient(baseUrl).create(ApiInterface.class);
        HashMap<String, String> queryParams = new HashMap<>();
        queryParams.put(APIConstants.KEY_EMAIL, sourceId + username.toLowerCase());
        queryParams.put(APIConstants.KEY_PASSWORD, Utils.encodePwd(password));


        Call<LoginResponse> call = apiService.getLoginResponse(queryParams);
        call.enqueue(new Callback<LoginResponse>() {

            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

                if (response.body().getResponseBean()==null) {
                    httpCallback.resultCallback(APIConstants.API_LOGIN, HttpCallback.REQUEST_TYPE_GET,
                            HttpCallback.RETURN_TYPE_FAILURE, 0,  response.body().getErrorBean());
                    return;
                }
                httpCallback.resultCallback(APIConstants.API_LOGIN, HttpCallback.REQUEST_TYPE_GET,
                        HttpCallback.RETURN_TYPE_SUCCESS, response.code(), response.body().getResponseBean());

            }


            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                // Log error here since request failed
                httpCallback.resultCallback(APIConstants.API_APP_VERIFICATION, HttpCallback.REQUEST_TYPE_GET,
                        HttpCallback.RETURN_TYPE_FAILURE, 0, t);
                t.printStackTrace();
            }
        });
    }

答案 1

因此,你将有来自同一终结点的两个不同的成功(状态代码 200)响应。一个是实际数据模型,一个是错误(两者都是json结构,如下所示?

有效的登录模板响应:

{
  "id": 1234,
  "something": "something"
}

错误响应

{
  "error": "error message"
}

您可以做的是让一个实体包装这两种情况并使用自定义反序列化程序。

class LoginBeanResponse {
  @Nullable private final LoginBean loginBean;
  @Nullable private final ErrorMessage errorMessage;

  LoginBeanResponse(@Nullable LoginBean loginBean, @Nullable ErrorMessage errorMessage) {
    this.loginBean = loginBean;
    this.errorMessage = errorMessage;
  }
  // Add getters and whatever you need
}

错误的包装器:

class ErrorMessage {
  String errorMessage;
  // And whatever else you need
  // ...
}

然后你需要一个:JsonDeserializer

public class LoginBeanResponseDeserializer implements JsonDeserializer<LoginBeanResponse> {

  @Override
  public LoginBeanResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    // Based on the structure you check if the data is valid or not
    // Example for the above defined structures:

    // Get JsonObject
    final JsonObject jsonObject = json.getAsJsonObject();
    if (jsonObject.has("error") {
      ErrorMessage errorMessage = new Gson().fromJson(jsonObject, ErrorMessage.class);
      return new LoginBeanResponse(null, errorMessage)
    } else {
      LoginBean loginBean = new Gson().fromJson(jsonObject, LoginBean.class):
      return new LoginBeanResponse(loginBean, null);
    }
  }
}

然后将此反序列化程序添加到 :GsonConverterFactory

GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(LoginBeanResponse.class, new LoginBeanResponseDeserializer()).create():

apiClient = new Retrofit.Builder()
    .baseUrl(url)
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .addConverterFactory(GsonConverterFactory.create(gsonBuilder))
    .client(httpClient)
    .build();

这是我能想到的让它工作的唯一方法。但如前所述,这种API设计是错误的,因为状态代码是有原因的。我仍然希望这有帮助。

编辑:然后,您可以在调用该改造的类中执行的操作(如果您已经使用RxJava从转换为)实际上返回了正确的错误。像这样:Call<LoginBeanResponse>Single<LoginBeanResponse>

Single<LoginBean> getLoginResponse(Map<String, String> queryMap) {
    restApi.getLoginResponse(queryMap)
        .map(loginBeanResponse -> { if(loginBeanResponse.isError()) {
            Single.error(new Throwable(loginBeanResponse.getError().getErrorMessage()))
        } else { 
            Single.just(loginBeanReponse.getLoginBean()) 
        }})
}

答案 2

你可以简单地通过这样做来做到这一点。

try
{
String error = response.errorBody().string();
error = error.replace("\"", "");
Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
e.printStackTrace();
}

推荐