Retrofit HTTP body返回为空的情况报错 EOFException

遇到HTTP请求code为200,response body为空的情况。
这种情况下,RetrofitGson解析阶段会出现报错。
Retrofit HTTP body返回为空的情况报错 EOFException_第1张图片
查看了Retrofit的GitHub后,找到了解决方案。

public class NullOnEmptyConverterFactory extends Converter.Factory {
    @Override
    public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
        return new Converter() {
            @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解析,以避免报错的情况。

详见Handle Empty Body

你可能感兴趣的:(空,null,EOFException,Android,Retrofit,Android)