我在应用程序中使用Retrofit从服务器下载一些JSON。但是有时候,当我从服务器请求重复数据时,它会返回带有空主体的响应代码208。但是在200中,我有一个不为空的响应主体。
在空主体中,改型使用onFailure方法。我的问题在这里!
我想知道请求失败的原因(这是因为208(就我而言)或其他原因)。如何在OnFailure方法中获取响应代码?

我试图实现自己的callBack方法,如下所示:

public class DefaultCallback<T> implements Callback<T> {

  private static final String TAG = "LOGO_SendReport";
  private Callback<T> callback;

  public DefaultCallback(Callback<T> callback) {
    this.callback = callback;
  }

  @Override
  public void onResponse(Call<T> call, Response<T> response) {
    if (response.body() == null) {

      callback.onFailure(call, new NullPointerException("Empty response"));
      Log.e(TAG, "Response code is: " + response.code());

    } else {
      callback.onResponse(call, response);
    }
  }

  @Override
  public void onFailure(Call<T> call, Throwable t) {
    Log.e(TAG, t.toString());
    callback.onFailure(call, t);
  }
}


这是我的电话:

 @POST("office/report")
  Call<ResponseSendReport> sendReport(@Body SendReport pendingList);


这是我的最终方法:

    final APIService service = ServiceGenerator.createService(APIService.class, App.Auth);

            Call<ResponseSendReport> call = service.sendReport(sendReport);

            call.enqueue(new Callback<ResponseSendReport>() {
              @Override
              public void onResponse(Call<ResponseSendReport> call, Response<ResponseSendReport> response) {

                Log.i("LOGO_SendReport", "code is:  " + response.code());


                if (response.code() == 200) {


              }

              @Override
              public void onFailure(Call<ResponseSendReport> call, Throwable t) {

                /*When Response code is 208 Goes here and I want to get
                 response code
                 if it is 208 to handle it! */
              }
            });


谢谢您的帮助。

最佳答案

您可以创建抽象类并处理案例。

public abstract class DefaultCallback<T> implements Callback<T> {

   @SuppressWarnings({"ConstantConditions", "unchecked"})
   @Override public void onResponse(@NonNull Call<T> call, Response<T> response) {
       if (response.isSuccessful()) {
           onSuccess(response.body(), response.code());
       } else {
           onError(response.errorBody(), response.code());
       }
   }

   @Override public void onFailure(@NonNull Call<T> call, @NonNull Throwable throwable) {
       onError(null, -1);
   }

   public abstract void onSuccess(@NonNull final T response, int code);

   public abstract void onError(@Nullable ResponseBody body, int code);
}

关于android - 如何通过改造创建新的CallBack,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46805320/

10-10 11:52