dio_client.dart 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:connectivity_plus/connectivity_plus.dart';
  4. import 'package:dio/dio.dart';
  5. import 'package:flutter/cupertino.dart';
  6. import 'package:logger/logger.dart';
  7. import 'package:naiyouwl/app/common/LogHelper.dart';
  8. import '../common/SharedPreferencesUtil.dart';
  9. //import 'custom_interceptors.dart';
  10. class DioClient {
  11. static final DioClient _instance = DioClient._internal();
  12. late Dio _dio;
  13. factory DioClient() => _instance;
  14. final Logger _logger = Logger();
  15. DioClient._internal() {
  16. _dio = Dio(BaseOptions(
  17. baseUrl: 'https://api.androidrj01.top', // 你的API地址
  18. connectTimeout: 5000,
  19. receiveTimeout: 3000,
  20. ));
  21. // 仅在调试模式下添加日志拦截器
  22. assert(() {
  23. _dio.interceptors.add(LogInterceptor(
  24. request: true,
  25. requestBody: true,
  26. responseBody: true,
  27. error: true,
  28. logPrint: _logger.d, // 使用 Logger 插件打印日志
  29. ));
  30. return true;
  31. }());
  32. final customInterceptor = CustomInterceptors(_dio);
  33. //token
  34. _dio.interceptors.add(TokenInterceptor());
  35. // 添加拦截器
  36. _dio.interceptors.add(customInterceptor);
  37. // 添加响应拦截器
  38. _dio.interceptors.add(InterceptorsWrapper(
  39. onResponse: (Response<dynamic> response, ResponseInterceptorHandler handler) {
  40. final responseData = response.data as Map<String, dynamic>;
  41. if (responseData['ret'] == 1) {
  42. customInterceptor.resetRetryCount(); // 当请求成功时重置重试计数器
  43. handler.next(
  44. Response<dynamic>(
  45. data: responseData['data'],
  46. headers: response.headers,
  47. requestOptions: response.requestOptions,
  48. statusCode: response.statusCode,
  49. ),
  50. );
  51. } else {
  52. handler.reject(
  53. DioError(
  54. requestOptions: response.requestOptions,
  55. error: AppException(message: responseData['msg'] ?? 'Unknown Error',statusCode: responseData['ret'] ?? -1),
  56. ),
  57. );
  58. }
  59. },
  60. ));
  61. }
  62. Dio get dio => _dio;
  63. }
  64. class TokenInterceptor extends Interceptor {
  65. // 这里假设您有一个方法来从安全存储中获取Token
  66. Future<String?> getToken() async {
  67. // 从您存储Token的地方获取Token,例如从SharedPreferences或SecureStorage
  68. String? token = await SharedPreferencesUtil().getString("token");
  69. return token;
  70. //return "Your_Token";
  71. }
  72. @override
  73. Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
  74. final token = await getToken();
  75. if (token != null) {
  76. options.headers["Authorization"] = "Bearer $token";
  77. }
  78. return super.onRequest(options, handler);
  79. }
  80. }
  81. class CustomInterceptors extends Interceptor {
  82. int _retryCount = 0;
  83. final List<String> _backupUrls = ['https://api.androidrj02.top','https://api.androidrj88.com','https://user.jyjksmd.top','https://api.androidrj03.top'];
  84. final Dio _dio; // 添加 Dio 作为参数
  85. CustomInterceptors(this._dio);
  86. Future<bool> isConnected() async {
  87. var connectivityResult = await (Connectivity().checkConnectivity());
  88. return connectivityResult != ConnectivityResult.none;
  89. }
  90. void resetRetryCount() {
  91. _retryCount = 0;
  92. }
  93. @override
  94. Future<void> onError(DioError err, ErrorInterceptorHandler handler) async {
  95. LogHelper().d("错误类型:==== ${err.type}");
  96. // 检查网络连接状态
  97. bool isConnectNetWork = await isConnected();
  98. if (!isConnectNetWork) {
  99. // 无网络连接,设置友好的错误消息
  100. err.error = AppException(message: "当前网络不可用,请检查您的网络");
  101. return handler.next(err);
  102. } else if (err.error is SocketException || err.error is DioError) {
  103. if (_retryCount < _backupUrls.length) {
  104. // 有网络连接但请求失败,尝试使用备用地址
  105. err.requestOptions.baseUrl = _backupUrls[_retryCount];
  106. LogHelper().d("切换地址:==== ${err.requestOptions.baseUrl}");
  107. try {
  108. final Response response = await _dio.fetch(err.requestOptions);
  109. return handler.resolve(response);
  110. } catch (e) {
  111. if (e is DioError) {
  112. _retryCount++;
  113. return onError(e, handler); // Recursive call
  114. } else {
  115. // Handle other exceptions if needed or rethrow them
  116. rethrow;
  117. }
  118. }
  119. }
  120. }
  121. // 其他错误,统一处理
  122. AppException appException = AppException.create(err);
  123. debugPrint('DioError===: ${appException.toString()}');
  124. err.error = appException;
  125. return handler.next(err);
  126. }
  127. }
  128. class AppException implements Exception {
  129. final int? statusCode; // 添加了 statusCode
  130. final String message;
  131. AppException({required this.message,this.statusCode});
  132. static AppException create(DioError err) {
  133. switch (err.type) {
  134. case DioErrorType.cancel:
  135. return AppException(message: '请求被取消');
  136. case DioErrorType.connectTimeout:
  137. return AppException(message: '连接超时');
  138. case DioErrorType.sendTimeout:
  139. return AppException(message: '请求超时');
  140. case DioErrorType.receiveTimeout:
  141. return AppException(message: '响应超时');
  142. case DioErrorType.response:
  143. return AppException(
  144. message: '服务器返回异常,状态码:${err.response?.statusCode}',
  145. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  146. );
  147. case DioErrorType.other:
  148. return AppException(
  149. message: '未知错误: ${err.message}',
  150. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  151. );
  152. default:
  153. return AppException(
  154. message: err.message,
  155. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  156. );
  157. }
  158. }
  159. @override
  160. String toString() {
  161. return message;
  162. }
  163. }
  164. extension DioClientExtension on DioClient {
  165. Future<dynamic> get(String path, {Map<String, dynamic>? queryParameters}) async {
  166. final response = await _dio.get(path, queryParameters: queryParameters);
  167. return _handleResponse(response);
  168. }
  169. Future<dynamic> post(String path, {Map<String, dynamic>? data}) async {
  170. final response = await _dio.post(path, data: data);
  171. return _handleResponse(response);
  172. }
  173. Future<dynamic> put(String path, {Map<String, dynamic>? data}) async {
  174. final response = await _dio.put(path, data: data);
  175. return _handleResponse(response);
  176. }
  177. Future<void> download(String urlPath, String savePath) async {
  178. await _dio.download(urlPath, savePath);
  179. }
  180. dynamic _handleResponse(Response response) {
  181. if (response.data is List) {
  182. return response.data as List<dynamic>;
  183. } else if (response.data is Map) {
  184. return response.data as Map<String, dynamic>;
  185. } else {
  186. throw Exception('Unsupported data type');
  187. }
  188. }
  189. }