改造 2 - 当响应状态为 422(不可处理的实体)时,响应正文为空

2024-02-01

我正在使用 Retrofit 在我的网络服务器中发出 POST 请求。

但是,当响应状态为时,我似乎无法获取响应正文422 (unprocessable entity)。响应主体始终是null.

我想知道我是否做错了什么或者是否有解决方法。因为我在请求中使用相同的 jsonPostman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop,并且它会正常返回主体。

这是方法:

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

主体是一个 JsonObject,我没有像文档所说的那样进行序列化。但我认为这不是问题所在。


默认情况下,当您的服务器返回错误代码时response.body()总是null。您正在寻找的是response.errorBody()。常见的方法是这样的:

    @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
        }
    }

如果您需要一些高级的东西,请看一下拦截器 https://github.com/square/okhttp/wiki/Interceptors and 如何使用它们 https://stackoverflow.com/questions/32963394/how-to-use-interceptor-to-add-headers-in-retrofit-2-0

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

改造 2 - 当响应状态为 422(不可处理的实体)时,响应正文为空 的相关文章

随机推荐