Retrofit2 OkHttp3响应体Null错误

时间:2017-05-27 13:30:33

标签: retrofit retrofit2 okhttp3

我正在使用Retrofit 2调用微服务,该微服务在PUT方法上返回200和空响应体。 然而,改造2似乎无法处理这个问题并且在#34;排队"去onFailure分支
@覆盖 public void onFailure(来电,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]

有谁知道是什么原因引起的?由于请求成功提供(见上文)。

1 个答案:

答案 0 :(得分: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())