How to Handle Two Different Response in Retrofit

断了今生、忘了曾经 提交于 2020-02-28 15:54:46

问题


I followed this to POST Data Using Retrofit2

I Used JSON POJO to Parse my POST and GET files

So Here If Data inside the Records Is there I will get This Kind of Response

{
"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."
    }
]
}

If there is no Data I will get

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

So Here I can eable to Parse the data which is there in the status 200 but when Status is not equals to 200 I want to Handle them

I tried with

   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
             }

now what should I write in Else I used response data in POJO which are not equals to 200 but I its asking for list

Update

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

回答1:


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

And Your callBack methods should be like

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



回答2:


You can achieve this by fetching errorBody() with help of Retrofit2.

Make one POJO model class with name RestErrorResponse.java For handle this Response.

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

And follow information given below:

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

I handled all failure response by this method. Hope this can also helps you.




回答3:


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();



回答4:


you can use different pojo class to handle error msg

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();
    }
}

success 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;
    }
}

error pojo class

public class ResponseError {
    public String status;
    public Response response;
    public class Response{
        public String msg;
    }
}


来源:https://stackoverflow.com/questions/51238140/how-to-handle-two-different-response-in-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!