找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 223|回复: 2

Android 如果确保网络超时10s一定返回

[复制链接]

1

主题

0

回帖

5

积分

新手上路

积分
5
发表于 2025-3-13 15:54:35 | 显示全部楼层 |阅读模式
按如下方式设置了网络超时,但是在某些网络环境下,超过60s 都没返回
  1. OkHttpClient client = new OkHttpClient.Builder()
  2.     .connectTimeout(10, TimeUnit.SECONDS)
  3.     .readTimeout(10, TimeUnit.SECONDS)
  4.     .writeTimeout(10, TimeUnit.SECONDS)
  5.     .build();
复制代码

70

主题

11

回帖

286

积分

管理员

积分
286
发表于 2025-3-13 16:56:41 | 显示全部楼层
除了超时时间,还需要控制重试次数
Okttp会跟踪网络情况,进行重试的,实际验证,默认重试次数是20次。默认重试机制可以参考代码RetryAndFollowUpInterceptor.
可以自定义控制重试次数,从而控制超时总时间:


  1. <div>
  2. <div>OkHttpClient client = new OkHttpClient.Builder()
  3.     .connectTimeout(10, TimeUnit.SECONDS)
  4.     .readTimeout(10, TimeUnit.SECONDS)
  5.     .writeTimeout(10, TimeUnit.SECONDS)
  6. <span style="white-space:pre">        </span>.addInterceptor(new RetryInterceptor(maxRentry))
  7. <span style="white-space:pre">        </span>.build();

  8. public static class RetryInterceptor implements Interceptor {        
  9.         private int maxRentry;

  10.         public RetryInterceptor(int maxRentry) {
  11.             this.maxRentry = maxRentry;
  12.         }

  13.         @NotNull
  14.         @Override
  15.         public Response intercept(@NotNull Chain chain) throws IOException {
  16.             return retry(chain, 0);
  17.         }

  18.         Response retry(Chain chain, int retryCent) {
  19.             Request request = chain.request();
  20.             Response response = null;
  21.             try {
  22.                 response = chain.proceed(request);
  23.             } catch (Exception e) {
  24.                 if (maxRentry > retryCent) {
  25.                    response = retry(chain, retryCent + 1);
  26.                 }
  27.             } finally {
  28.                 return response;
  29.             }
  30.         }
  31.     }</div>
  32. </div>
复制代码


0

主题

4

回帖

10

积分

新手上路

积分
10
发表于 2025-3-17 20:12:39 | 显示全部楼层
还可以简单点,自定义一个超时定时器,比如超过10s就cancel okhttp的请求。
我就是这样实现的
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|软件开发

GMT+8, 2025-8-27 19:53 , Processed in 0.135282 second(s), 20 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表