不适用于使用注释的翻新拦截器的OkHttp调用超时

时间:2018-11-21 14:03:24

标签: android retrofit retrofit2 okhttp okhttp3

我正在尝试使用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)

这是因为必须在呼叫入队之前设置呼叫超时? (并且拦截器在此过程中触发得太晚了?),或者这还有其他吗?

1 个答案:

答案 0 :(得分:2)

很遗憾,您是对的。这是因为OkHttpClient在执行拦截器链之前会超时。如果您查看okhttp3.RealCall类中的Response execute()方法,您会发现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();

祝你好运!