Retrofit2:EOFException使用拦截器处理响应

问题描述

我正在打个电话,没有人回来。调用成功,但是拦截器失败,出现EOFException,并且调用了回调的onFailure而不是onResponse。

日志:

OkHttp: <-- 200 undefined https://www.example.com/abc/eventlog (648ms)

W/System.err: java.io.EOFException
W/System.err:     at okio.RealBufferedSource.require(RealBufferedSource.java:65)
W/System.err:     at okio.GzipSource.consumeHeader(GzipSource.java:114)
W/System.err:     at okio.GzipSource.read(GzipSource.java:73)
W/System.err:     at okio.RealBufferedSource.request(RealBufferedSource.java:72)
W/System.err:     at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:238)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
W/System.err:     at com.abc.mobile.data.remote.MyInterceptor.intercept(MyInterceptor.java:37)

MyInterceptor.java

中的第37行
@Override
public Response intercept(Chain chain) throws IOException {
    Response response = chain.proceed(chain.request()); <--- line 37
    …
    …
}

ApiInterface:

@POST("{end_point}")
    Call<String> postRequest(@HeaderMap Map<String,String> map,@Path(value = "end_point",encoded = true) String endPoint,@QueryMap(encoded = true) Map<String,String> queryMap,@Body String json);

我尝试过NullOnEmptyConverterFactory这样的方法

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);
        };
    }
}

private Retrofit getRetrofitInstance(String webHostUrl) {

return new Retrofit.Builder()
        .baseUrl(webHostUrl)
        .addConverterFactory(new NullOnEmptyConverterFactory())
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .client(getokHttpClient())
        .build();
}

但这会导致异常,表明intercept()方法返回空值

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)