|
发表于 2025-3-13 16:56:41
|
显示全部楼层
除了超时时间,还需要控制重试次数
Okttp会跟踪网络情况,进行重试的,实际验证,默认重试次数是20次。默认重试机制可以参考代码RetryAndFollowUpInterceptor.
可以自定义控制重试次数,从而控制超时总时间:
- <div>
- <div>OkHttpClient client = new OkHttpClient.Builder()
- .connectTimeout(10, TimeUnit.SECONDS)
- .readTimeout(10, TimeUnit.SECONDS)
- .writeTimeout(10, TimeUnit.SECONDS)
- <span style="white-space:pre"> </span>.addInterceptor(new RetryInterceptor(maxRentry))
- <span style="white-space:pre"> </span>.build();
- public static class RetryInterceptor implements Interceptor {
- private int maxRentry;
-
- public RetryInterceptor(int maxRentry) {
- this.maxRentry = maxRentry;
- }
-
- @NotNull
- @Override
- public Response intercept(@NotNull Chain chain) throws IOException {
- return retry(chain, 0);
- }
-
- Response retry(Chain chain, int retryCent) {
- Request request = chain.request();
- Response response = null;
- try {
- response = chain.proceed(request);
- } catch (Exception e) {
- if (maxRentry > retryCent) {
- response = retry(chain, retryCent + 1);
- }
- } finally {
- return response;
- }
- }
- }</div>
- </div>
复制代码
|
|