dio_client.dart 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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) async {
  40. final responseData = response.data as Map<String, dynamic>;
  41. if (responseData['ret'] == 1) {
  42. customInterceptor.resetRetryCount(); // 当请求成功时重置重试计数器
  43. await SharedPreferencesUtil().setString("last_successful_url", response.requestOptions.baseUrl);
  44. handler.next(
  45. Response<dynamic>(
  46. data: responseData['data'],
  47. headers: response.headers,
  48. requestOptions: response.requestOptions,
  49. statusCode: response.statusCode,
  50. ),
  51. );
  52. } else {
  53. handler.reject(
  54. DioError(
  55. requestOptions: response.requestOptions,
  56. error: AppException(message: responseData['msg'] ?? 'Unknown Error',statusCode: responseData['ret'] ?? -1),
  57. ),
  58. );
  59. }
  60. },
  61. ));
  62. }
  63. void updateBaseUrl(String newBaseUrl) {
  64. _dio.options.baseUrl = newBaseUrl;
  65. }
  66. Dio get dio => _dio;
  67. }
  68. class TokenInterceptor extends Interceptor {
  69. // 这里假设您有一个方法来从安全存储中获取Token
  70. Future<String?> getToken() async {
  71. // 从您存储Token的地方获取Token,例如从SharedPreferences或SecureStorage
  72. String? token = await SharedPreferencesUtil().getString("token");
  73. return token;
  74. //return "Your_Token";
  75. }
  76. @override
  77. Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
  78. final token = await getToken();
  79. if (token != null) {
  80. options.headers["Authorization"] = "Bearer $token";
  81. }
  82. return super.onRequest(options, handler);
  83. }
  84. }
  85. class CustomInterceptors extends Interceptor {
  86. int _retryCount = 0;
  87. final List<String> _backupUrls = ['https://api.androidrj02.top','https://api.androidrj88.com','https://user.jyjksmd.top','https://api.androidrj03.top'];
  88. final Dio _dio; // 添加 Dio 作为参数
  89. CustomInterceptors(this._dio);
  90. Future<bool> isConnected() async {
  91. var connectivityResult = await (Connectivity().checkConnectivity());
  92. return connectivityResult != ConnectivityResult.none;
  93. }
  94. void resetRetryCount() {
  95. _retryCount = 0;
  96. }
  97. @override
  98. Future<void> onError(DioError err, ErrorInterceptorHandler handler) async {
  99. LogHelper().d("onError === $_retryCount");
  100. // 检查网络连接状态
  101. bool isConnectNetWork = await isConnected();
  102. if (!isConnectNetWork) {
  103. // 无网络连接,设置友好的错误消息
  104. err.error = AppException(message: "当前网络不可用,请检查您的网络");
  105. return handler.next(err);
  106. } else if (err.error is SocketException || err.type == DioErrorType.other || err.type == DioErrorType.connectTimeout || err.type == DioErrorType.sendTimeout || err.type == DioErrorType.receiveTimeout) {
  107. LogHelper().d("错误类型:==== ${err.type}");
  108. if (_retryCount < _backupUrls.length) {
  109. // 有网络连接但请求失败,尝试使用备用地址
  110. err.requestOptions.baseUrl = _backupUrls[_retryCount];
  111. LogHelper().d("切换地址:==== ${err.requestOptions.baseUrl}");
  112. _retryCount++;
  113. try {
  114. final Response response = await _dio.fetch(err.requestOptions);
  115. return handler.resolve(response);
  116. } catch (e) {
  117. if (e is DioError) {
  118. return onError(e, handler); // Recursive call
  119. } else {
  120. // Handle other exceptions if needed or rethrow them
  121. rethrow;
  122. }
  123. }
  124. }
  125. }
  126. // 其他错误,统一处理
  127. AppException appException = AppException.create(err);
  128. debugPrint('DioError===: ${appException.toString()}');
  129. err.error = appException;
  130. return handler.next(err);
  131. }
  132. }
  133. class AppException implements Exception {
  134. final int? statusCode; // 添加了 statusCode
  135. final String message;
  136. AppException({required this.message,this.statusCode});
  137. static AppException create(DioError err) {
  138. switch (err.type) {
  139. case DioErrorType.cancel:
  140. return AppException(message: '请求被取消');
  141. case DioErrorType.connectTimeout:
  142. return AppException(message: '连接超时');
  143. case DioErrorType.sendTimeout:
  144. return AppException(message: '请求超时');
  145. case DioErrorType.receiveTimeout:
  146. return AppException(message: '响应超时');
  147. case DioErrorType.response:
  148. return AppException(
  149. message: '服务器返回异常,状态码:${err.response?.statusCode}',
  150. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  151. );
  152. case DioErrorType.other:
  153. return AppException(
  154. message: '网络连接失败',
  155. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  156. );
  157. default:
  158. return AppException(
  159. message: err.message,
  160. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  161. );
  162. }
  163. }
  164. @override
  165. String toString() {
  166. return message;
  167. }
  168. }
  169. extension DioClientExtension on DioClient {
  170. Future<dynamic> get(String path, {Map<String, dynamic>? queryParameters}) async {
  171. final response = await _dio.get(path, queryParameters: queryParameters);
  172. return _handleResponse(response);
  173. }
  174. Future<dynamic> post(String path, {Map<String, dynamic>? data}) async {
  175. final response = await _dio.post(path, data: data);
  176. return _handleResponse(response);
  177. }
  178. Future<dynamic> put(String path, {Map<String, dynamic>? data}) async {
  179. final response = await _dio.put(path, data: data);
  180. return _handleResponse(response);
  181. }
  182. Future<void> download(String urlPath, String savePath) async {
  183. await _dio.download(urlPath, savePath);
  184. }
  185. dynamic _handleResponse(Response response) {
  186. if (response.data is List) {
  187. return response.data as List<dynamic>;
  188. } else if (response.data is Map) {
  189. return response.data as Map<String, dynamic>;
  190. } else {
  191. throw Exception('Unsupported data type');
  192. }
  193. }
  194. }