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

前端 未结 9 1894
旧巷少年郎
旧巷少年郎 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:53

    Here is the simplest solution,

    If you want to handle the response from onFailure method:

    @Override
    public void onFailure(Call call, Throwable t) {
        HttpException httpException = (HttpException) t;
        String errorBody = httpException.response().errorBody().string();
        // use Gson to parse json to your Error handling model class
        ErrorResponse errorResponse = Gson().fromJson(errorBody, ErrorResponse.class);
    }
    

    Or if you are using rxjava Observable with Kotlin, handle it from error body:

    { error ->
        val httpException :HttpException = error as HttpException
        val errorBody: String = httpException.response().errorBody()!!.string()
        // use Gson to parse json to your Error handling model class
        val errorResponse: ErrorResponse = 
           Gson().fromJson(errorBody, ErrorResponse::class.java)
    }
    

    Don't forget to properly handle json to class conversion (use try-catch if not sure).

提交回复
热议问题