Retrofit2 OkHttp3响应正文空错误

问题描述:

我正在使用Retrofit 2来调用一个微服务,它返回一个200和一个PUT方法上的空响应主体。 改造2但似乎不能够处理这一点,并在“排队”进入到onFailure处分支
@覆盖 公共无效onFailure处(电话呼叫,的Throwable T){Retrofit2 OkHttp3响应正文空错误

下面是日志:

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: [email protected]; line: 1, column: 0] 

任何人都知道是什么原因造成的?由于请求已成功发送(请参见上文)。

+0

这是相当奇怪之前添加该转换器。您的电话是否会返回任何可能会尝试进行反序列化的对象?通过电话我的意思是java界面 – Fred

+0

你找到解决方案吗?我面临同样的问题。看起来这是一些杰克逊版本发生。你正在使用哪个版本? – Pawan

+0

嗨,是的,你需要像这里https://github.com/square/retrofit/issues/1554 – razvan

我创建了一个空的处理程序转换器针对此问题:

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())