我正在尝试使用OkHttp 3.12.0中最近添加的功能:全操作超时。为此,我还依赖于翻新2.5.0中的新Invocation
类,它允许我检索方法注释。
注释是:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Timeout {
int value();
TimeUnit unit();
}
改造界面是:
public interface AgentApi {
@Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
@GET("something")
Call<String> getSomething();
}
拦截器是:
class TimeoutInterceptor implements Interceptor {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
final Invocation tag = request.tag(Invocation.class);
final Method method = tag != null ? tag.method() : null;
final Timeout timeout = method != null ? method.getAnnotation(Timeout.class) : null;
if (timeout != null) {
chain.call().timeout().timeout(timeout.value(), timeout.unit());
}
return chain.proceed(request);
}
}
我已经在提供给Retrofit Builder的OkHttpClient中正确添加了带有.addInterceptor(...)
的TimeoutInterceptor。
不幸的是,它没有像我预期的那样工作。达到超时后,呼叫不会失败?
虽然它在使用拦截器的链方法时工作正常:
chain
.withConnectTimeout(connect, unit)
.withReadTimeout(read, unit)
.withWriteTimeout(write, unit)
这是因为必须在呼叫排队之前设置呼叫超时吗? (并且Interceptor在这个过程中被触发得太晚了?),还是这个呢?
不幸的是你是对的。这是因为OkHttpClient
在执行拦截器链之前会超时。如果你看看Response execute()
类中的okhttp3.RealCall方法,你会发现timeout.enter()
调度超时的行OkHttp
,它是在执行拦截器的地方getResponseWithInterceptorChain()
之前调用的。
幸运的是,你可以为此编写解决方法:)将你的TimeoutInterceptor
放在okhttp3
包中(你可以在你的应用程序中创建该包)。这将允许您访问具有包可见性的RealCall
对象。你的TimeoutInterceptor
课程应该如下所示:
package okhttp3;
public class TimeoutInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Invocation tag = request.tag(Invocation.class);
Method method = tag != null ? tag.method() : null;
Timeout timeout = method != null ? method.getAnnotation(Timeout.class) : null;
if (timeout != null) {
chain.call().timeout().timeout(timeout.value(), timeout.unit());
RealCall realCall = (RealCall) chain.call();
realCall.timeout.enter();
}
return chain.proceed(request);
}
}
解决方法包括在更改超时后再次执行timeout.enter()
。所有魔法都发生在线上:
RealCall realCall = (RealCall) chain.call();
realCall.timeout.enter();
祝好运!