How to Handle Two Different Response in Retrofit

前端 未结 4 571
青春惊慌失措
青春惊慌失措 2021-01-06 08:10

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

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 08:52

    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.

提交回复
热议问题