Retrofit 中如何处理两种不同的响应

How to Handle Two Different Response in Retrofit

我跟随 this 到 POST 使用 Retrofit2 的数据

我使用 JSON POJO 解析我的 POST 和 GET 文件

所以如果记录中的数据在那里,我会得到这种响应

{
"status": "200",
"response": [{
        "cnt_id": "201",
        "phn_no": "3251151515",
        "dat_cnt": "Reset Password request Said to Mail"
    },
    {
        "cnt_id": "209",
        "phn_no": "555465484684",
        "dat_cnt": "Hi DEMO User , Congratulations! Your account has been created successfully."
    },
    {
        "cnt_id": "210",
        "phn_no": "4774748",
        "dat_cnt": "Hi XYZ , Congratulations! Your account has been created successfully."
    }
]
}

如果没有数据我会得到

{"status":"204","response":{"msg":"No Content"}}
{"status":"400","response":{"msg":"BadRequest"}}
{"status":"401","response":{"msg":"Unauthorized User"}}

所以在这里我可以解析状态 200 中的数据,但是当状态不等于 200 时我想处理它们

我试过

   status = response.body().getStatus();
   if(status.equals("200")) {
      List<Response> resList =  response.body(). getResponse();

            for(int i = 0; i<resList.size(); i++)
            {.
             .
              ..
             .
            }
        }

        else {
             //not Implemented
             }

现在我应该写什么否则我在 POJO 中使用了不等于 200 的响应数据但我要求列表

更新

com.example.Example.java

public class Example {
    @SerializedName("status") @Expose private String status;
    @SerializedName("response") @Expose private List<Response> response = null;
}        

com.example.Response.java

public class Response {
    @SerializedName("cnt_id") @Expose private String cntId;
    @SerializedName("phn_no") @Expose private String phnNo;
    @SerializedName("dat_cnt") @Expose private String datCnt;
}
class Response<T> {
        private String status;
        private T response;

        private boolean isSuccess() {
            return status.equals("200");
        }
    }

    class ListData {
        private String cnt_id;
        private String phn_no;
        private String dat_cnt;
    }

    class Error {
        private String msg;
    }

    public class MainResponse {
        @SerializedName("Error")
        private Error error;
        @SerializedName("AuthenticateUserResponse")
        private List<ListData> listData;
    }

@POST("listData")
Call<Response<MainResponse>> listData();

您可以通过在 Retrofit2 的帮助下获取 errorBody() 来实现此目的。

创建一个 POJO 模型 class,名称为 RestErrorResponse.java 用于处理此响应。

{"status":"401","response":{"msg":"Unauthorized User"}}

并遵循以下信息:

 if (response.isSuccessful()) {

        // Your Success response. 

 } else {

        // Your failure response. This will handles 400, 401, 500 etc. failure response code


         Gson gson = new Gson();
         RestErrorResponse errorResponse = gson.fromJson(response.errorBody().charStream(), RestErrorResponse.class);
                    if (errorResponse.getStatus() == 400) {
                        //DO Error Code specific handling

                        Global.showOkAlertWithMessage(YourClassName.this,
                                getString(R.string.app_name),
                                strError);

                    } else {
                        //DO GENERAL Error Code Specific handling
                    }
                }

我用这种方法处理了所有的失败响应。希望这也可以帮助你。

您可以使用不同的 pojo class 来处理错误消息

status = response.body().getStatus();
if(status.equals("200")) {
    ResponseSuccess res =  response.body();
    for(int i = 0; i < res.response.size(); i++){
        Log.d("TAG", "Phone no. " + res.response.get(i).phn_no);
    }
} else {
    Converter<ResponseBody, ResponseError> converter = getRetrofitInstance().responseBodyConverter(ResponseError.class, new Annotation[0]);
    ResponseError error;
    try {
        error = converter.convert(response.errorBody());
        Log.e("TAG", error.response.msg);
    } catch (IOException e) {
        error = new ResponseError();
    }
}

成功 pojo class

public class ResponseSuccess {
    public String status;
    public List<Response> response;
    public class Response{
        public String cnt_id;
        public String phn_no;
        public String dat_cnt;
    }
}

错误提示class

public class ResponseError {
    public String status;
    public Response response;
    public class Response{
        public String msg;
    }
}
public class Example {
    @SerializedName("status") @Expose private String status;
    @SerializedName("response") @Expose private Object response = null;
}

public class Response {
    @SerializedName("cnt_id") @Expose private String cntId;
    @SerializedName("phn_no") @Expose private String phnNo;
    @SerializedName("dat_cnt") @Expose private String datCnt;
}

public class ResponseError{
    @SerializedName("msg") @Expose private String msg;
}

你的回调方法应该像

new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> response) {
                if(response.isSuccessful()){
                    Example example = response.body();
                    Gson gson = new GsonBuilder().create();
                    if(example.status.equals("200")) {
                        TypeToken<List<Response>> responseTypeToken = new TypeToken<List<Response>>() {};
                        List<Response> responseList = gson.fromJson(gson.toJson(example.getResponse()), responseTypeToken.getType());
                    } else {
                        //If for everyOther Status the response is Object of ResponseError which contains msg.
                        ResponseError responseError = gson.fromJson(gson.toJson(example.getResponse()), ResponseError.class);
                    }
                }
            }

            @Override
            public void onFailure(Call<Example> call, Throwable t) {
                //Failure message
            }
        }

因此,在您的情况下,有可能获得 String/List<Response> 类型的响应标签。所以您将响应标记类型声明为 Object

@SerializedName("response") @Expose public Object response;

并按照代码片段在改造的onResponse方法中编写代码

if (response.body().response!=null &&  response.body().response instanceof Collection<?>) {
            //if you find response type is collection then convert to json then json to real collection object
            String responseStr = new Gson().toJson(data.diagnosis.provisionalDiagnosis);
            Type type=new TypeToken<List<Response>>(){}.getType();
            List<Response> responseList=new Gson().fromJson(responseStr,type);
            if(responseList.size() > 0){
                binding.phoneTv.setText(responseList.get(0).phnNo);
            }
        }

我发现这是处理具有多种类型的单个标签的简单方法