Appearance
为什么要使用网络自动重试
在开发Flutter应用时,网络请求失败是常见的问题。如果网络请求失败,用户可能会感到沮丧,甚至放弃使用应用。为了提高用户体验,我们可以使用网络自动重试机制,在请求失败时自动重新尝试请求,直到请求成功为止。
Dio
借助DIO,你可以直接实现。Dio Smart Retry.
只需要在dio网络请求拦截器中,增加以下的代码,即可完成此项优化。
dart
final dio = Dio();
// Add the interceptor
dio.interceptors.add(RetryInterceptor(
dio: dio,
logPrint: print, // specify log function (optional)
retries: 3, // retry count (optional)
retryDelays: const [ // set delays between retries (optional)
Duration(seconds: 1), // wait 1 sec before first retry
Duration(seconds: 2), // wait 2 sec before second retry
Duration(seconds: 3), // wait 3 sec before third retry
],
));
/// Sending a failing request for 3 times with 1s, then 2s, then 3s interval
await dio.get('https://mock.codes/500');
默认可重试状态代码
默认情况下将重试具有这些 http 状态代码的响应:
- 408:请求超时
- 429:请求过多
- 500:内部服务器错误
- 502错误的网关
- 503:服务不可用
- 504:网关超时
- 440:登录超时(IIS)
- 460:ClientClosedRequest(AWS 弹性负载均衡器)
- 499:客户端关闭请求(ngnix)
- 520:WebServerReturnedUnknownError
- 521:Web服务器宕机
- 522:连接超时
- 523:OriginIsUnreachable
- 524:发生超时
- 525:SSL握手失败
- 527:电磁炮错误
- 598:网络读取超时错误
- 599:NetworkConnectTimeoutError 可以覆盖此列表