改造2-响应状态为422(不可处理实体)时,响应主体为null [英] Retrofit 2 - Response body null when response status is 422 (unprocessable entity)
问题描述
我正在使用Retrofit在Web服务器中发出POST请求.
I'm using Retrofit to make a POST Request in my web server.
但是,当响应状态为422 (unprocessable entity)
时,我似乎无法获得响应正文.响应正文始终为null
.
However, I can't seem to get the response body when the response status is 422 (unprocessable entity)
. The response body is always null
.
我想知道我是否做错了什么,或者是否有解决方法.因为我在请求中使用了与邮递员的相同json,并且它正常返回身体.
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.
这是方法:
@Headers("Content-Type: application/vnd.api+json")
@POST("my_endpoint")
Call<JsonObject> postEntry(@Header("Authorization") String authorization, @Body JsonObject json);
主体是一个JsonObject,我没有像文档所说的那样进行序列化.但是我不认为这是问题所在.
The body is a JsonObject, I'm not serializing like the documentation say. But I don't think this is the problem.
推荐答案
默认情况下,服务器返回错误代码response.body()
时始终为null
.您要查找的是response.errorBody()
.常见的方法是这样的:
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 that
} else {
response.errorBody(); // do something with that
}
}
If you need something really advanced take a look at Interceptors and how to use them
这篇关于改造2-响应状态为422(不可处理实体)时,响应主体为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!