【问题标题】:Retrofit2 OkHttp3 Response Body Null ErrorRetrofit2 OkHttp3 响应正文空错误
【发布时间】:2017-10-28 06:49:48
【问题描述】:

我正在使用 Retrofit 2 调用一个微服务,该微服务在 PUT 方法上返回一个 200 和一个空响应体。 然而,改造 2 似乎无法处理这个问题,并且在“入队”中转到 onFailure 分支
@覆盖 public void onFailure(Call call, Throwable t) {

这里是日志:

Mai 27, 2017 3:26:49 PM okhttp3.internal.platform.Platform log
INFORMATION: --> PUT http://127.0.0.1/test/ http/1.1
Mai 27, 2017 3:26:49 PM okhttp3.internal.platform.Platform log
INFORMATION: Content-Type: application/vnd.tipico.notification-v1+json
Mai 27, 2017 3:26:49 PM okhttp3.internal.platform.Platform log
INFORMATION: Content-Length: 87
Mai 27, 2017 3:26:49 PM okhttp3.internal.platform.Platform log
INFORMATION: 
Mai 27, 2017 3:26:49 PM okhttp3.internal.platform.Platform log
INFORMATION: {"state":"ACTIVE","externalId":"abcd","loginName":"gsdfgsdf","updatedAt":1495531062000}
Mai 27, 2017 3:26:49 PM okhttp3.internal.platform.Platform log
INFORMATION: --> END PUT (87-byte body)
Mai 27, 2017 3:26:50 PM okhttp3.internal.platform.Platform log
INFORMATION: <-- 200  http://127.0.0.1/test/ (197ms)
Mai 27, 2017 3:26:50 PM okhttp3.internal.platform.Platform log
INFORMATION: X-Application-Context: customer-care-notification-service:49980
Mai 27, 2017 3:26:50 PM okhttp3.internal.platform.Platform log
INFORMATION: Content-Length: 0
Mai 27, 2017 3:26:50 PM okhttp3.internal.platform.Platform log
INFORMATION: Date: Sat, 27 May 2017 13:26:49 GMT
Mai 27, 2017 3:26:50 PM okhttp3.internal.platform.Platform log
INFORMATION: <-- END HTTP (0-byte body)
15:26:50,030 ERROR com.test.app.Test - Failed CCNS call com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: okhttp3.ResponseBody$BomAwareReader@9eb187b; line: 1, column: 0]

有人知道这是什么原因吗?由于请求已成功处理(见上文)。

【问题讨论】:

标签: retrofit retrofit2 okhttp3


【解决方案1】:

我为此问题创建了一个 Null 处理程序转换器:

public class NullOnEmptyConverterFactory extends Converter.Factory {

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
        return (Converter<ResponseBody, Object>) body -> {
            if (body.contentLength() == 0) return null;
            return delegate.convert(body);
        };
    }
}

您需要在 Gson 转换器之前添加此转换器

.addConverterFactory(new NullOnEmptyConverterFactory())

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2016-06-29
    • 2016-11-17
    • 2021-07-20
    • 2017-02-25
    • 1970-01-01
    • 2020-11-12
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多