遇到HTTP请求code为200,response body为空的情况。
这种情况下,RetrofitGson解析阶段会出现报错。
查看了Retrofit的GitHub后,找到了解决方案。
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 new Converter<ResponseBody, Object>() {
@Override
public Object convert(ResponseBody body) throws IOException {
long contentLength = body.contentLength();
if (contentLength == 0) {
return null;
}
return delegate.convert(body);
}
};
}
}
然后添加到Retrofit中
Retrofit retrofit = new Retrofit.Builder()
.endpoint(..)
.addConverterFactory(new NullOnEmptyConverterFactory()) //必须是要第一个
.addConverterFactory(GsonConverterFactory.create())
.build();
然后,如果HTTP body返回空,就会直接返回null,而不会进行Gson解析,以避免报错的情况。