Retrofit 2 - Response body null when response status is 422 (unprocessable entity)

前端 未结 3 1447
野性不改
野性不改 2021-02-19 02:37

I\'m using Retrofit to make a POST Request in my web server.

However, I can\'t seem to get the response body when the response status is 422 (unprocessable entit

3条回答
  •  死守一世寂寞
    2021-02-19 03:11

    By default, when your server is returning an error code response.body() is always null. What you are looking for is response.errorBody(). A common approach would be something like this:

        @Override
        public void onResponse(Response response, Retrofit retrofit) {
            if (response.isSuccess()) {
                response.body(); // do something with this
            } else {
                response.errorBody(); // do something with that
            }
        }
    

    If you need something advanced take a look at Interceptors and how to use them

提交回复
热议问题