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

前端 未结 9 1875
旧巷少年郎
旧巷少年郎 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 02:52

    This is how you can handle the response message I am handling for error 500 you can add as much you want

                    switch (response.code()) {
                        case HttpURLConnection.HTTP_OK:
                            break;
                        case HttpURLConnection.HTTP_UNAUTHORIZED:
                            callback.onUnAuthentic();
                            break;
                        case HttpURLConnection.HTTP_INTERNAL_ERROR:
                            try {
                                String errorResponse = response.errorBody().string();
                                JSONObject object = new JSONObject(errorResponse);
                                String message = "Error";
                                if (object.has("Message"))
                                    message = String.valueOf(object.get("Message"));
                                callback.onError(message);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                        case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
                        default:
                            callback.onNetworkError();
                            break;
                    }
    

提交回复
热议问题