首页 > 解决方案 > OkHttp 调用超时,包括或不包括拦截器重试次数

问题描述

我正在尝试使用 OkHttpClient 进行 HTTP 调用。我正在尝试在客户端上实现重试,以防我看到 SocketTimeoutExceptions。这是我所拥有的:

  builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            // try the request
            Response response = null;
            int tryCount = 1;
            while (tryCount <= MAX_TRY_COUNT) {
                try {
                    response = chain.proceed(request);
                    break;
                } catch (Exception e) {
                    if (!NetworkUtils.isNetworkAvailable()) {
                        // if no internet, dont bother retrying request
                        throw e;
                    }
                    if ("Canceled".equalsIgnoreCase(e.getMessage())) {
                        // Request canceled, do not retry
                        throw e;
                    }
                    if (tryCount >= MAX_TRY_COUNT) {
                        // max retry count reached, giving up
                        throw e;
                    }

                    try {
                        // sleep delay * try count (e.g. 1st retry after 3000ms, 2nd after 6000ms, etc.)
                        Thread.sleep(RETRY_BACKOFF_DELAY * tryCount);
                    } catch (InterruptedException e1) {
                        throw new RuntimeException(e1);
                    }
                    tryCount++;
                }
            }

            // otherwise just pass the original response on
            return response;
        }
    })
     .callTimeout(5000)
     .build()

我感到困惑的部分是 - 5000ms 超时是单次不包括重试,还是包括重试?

标签: retrofitokhttp

解决方案


没关系,在这里找到答案 - https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/

“如果呼叫需要重定向或重试,所有都必须在一个超时期限内完成。”


推荐阅读