Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 entity). The response body is always null.

I want to know if I'm doing something wrong or if there's a workaround for this. Because I'm using the same json in the request with Postman, and it returns the body normally.

This is the method:

@Headers("Content-Type: application/vnd.api+json")
@POST("my_endpoint")
Call<JsonObject> postEntry(@Header("Authorization") String authorization, @Body JsonObject json);

The body is a JsonObject, I'm not serializing like the documentation say. But I don't think this is the problem.

like image 244
Erick Filho Avatar asked Dec 07 '15 18:12

Erick Filho


2 Answers

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<JsonObject> 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

like image 100
tochkov Avatar answered Oct 23 '22 06:10

tochkov


I got the same error. My API was working using POSTMAN request but not working from Android retrofit call.

At first I was trying using @Field but it was getting error but later I've tried with @Body and it worked.

Sample Retrofit interface call

@POST("api/v1/app/instance")
Call<InstanceResponse> updateTokenValue(
        @HeaderMap Map<String, String> headers,
        @Body String body); 

and API calling code is:

 Map<String, String> headerMap=new HashMap<>();
        headerMap.put("Accept", "application/json");
        headerMap.put("Content-Type", "application/json");
        headerMap.put("X-Authorization","access_token");

        Map<String, String> fields = new HashMap<>();
        fields.put("app_name", "video");
        fields.put("app_version", "2.0.0");
        fields.put("firebase_token", "token");
        fields.put("primary", "1");

        ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<InstanceResponse> call = apiInterface.updateTokenValue(
                headerMap,new Gson().toJson(fields));
like image 34
Swapon Avatar answered Oct 23 '22 07:10

Swapon