Retrofit 2.0 - How to get response body for 400 Bad Request error?

前端 未结 9 1871
旧巷少年郎
旧巷少年郎 2021-01-31 02:33

So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.

{
    \"userMessage\": \"Blah\",
    \"internalMessage\": \"Bad Re         


        
9条回答
  •  囚心锁ツ
    2021-01-31 03:15

    You can try the below code to get 400 response. You can get error response from errorBody() method.

    Call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            //get success and error response here
     if (response.code() == 400) {
                    if(!response.isSuccessful()) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.errorBody().string());
                            String userMessage = jsonObject.getString("userMessage");
                            String internalMessage = jsonObject.getString("internalMessage");
                            String errorCode = jsonObject.getString("errorCode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
    
        @Override
        public void onFailure(Call call, Throwable t) {
            //get failure response here
        }
    }
    }
    

    EDIT: Fixed method name from toString to string

提交回复
热议问题