dio_client.dart 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 '../common/SharedPreferencesUtil.dart';
  8. //import 'custom_interceptors.dart';
  9. class DioClient {
  10. static final DioClient _instance = DioClient._internal();
  11. late Dio _dio;
  12. factory DioClient() => _instance;
  13. final Logger _logger = Logger();
  14. DioClient._internal() {
  15. _dio = Dio(BaseOptions(
  16. baseUrl: 'https://api.androidrj01.top', // 你的API地址
  17. connectTimeout: 5000,
  18. receiveTimeout: 3000,
  19. ));
  20. // 仅在调试模式下添加日志拦截器
  21. assert(() {
  22. _dio.interceptors.add(LogInterceptor(
  23. request: true,
  24. requestBody: true,
  25. responseBody: true,
  26. error: true,
  27. logPrint: _logger.d, // 使用 Logger 插件打印日志
  28. ));
  29. return true;
  30. }());
  31. final customInterceptor = CustomInterceptors(_dio);
  32. //token
  33. _dio.interceptors.add(TokenInterceptor());
  34. // 添加拦截器
  35. _dio.interceptors.add(customInterceptor);
  36. _dio.interceptors.add(InterceptorsWrapper(
  37. onResponse: (Response<dynamic> response, ResponseInterceptorHandler handler) {
  38. customInterceptor.resetRetryCount(); // 当请求成功时重置重试计数器
  39. handler.next(response);
  40. }
  41. ));
  42. // 添加响应拦截器
  43. _dio.interceptors.add(InterceptorsWrapper(
  44. onResponse: (Response<dynamic> response, ResponseInterceptorHandler handler) {
  45. final responseData = response.data as Map<String, dynamic>;
  46. if (responseData['ret'] == 1) {
  47. handler.next(
  48. Response<dynamic>(
  49. data: responseData['data'],
  50. headers: response.headers,
  51. requestOptions: response.requestOptions,
  52. statusCode: response.statusCode,
  53. ),
  54. );
  55. } else {
  56. handler.reject(
  57. DioError(
  58. requestOptions: response.requestOptions,
  59. error: AppException(message: responseData['msg'] ?? 'Unknown Error',statusCode: responseData['ret'] ?? -1),
  60. ),
  61. );
  62. }
  63. },
  64. ));
  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. // 检查网络连接状态
  100. bool isConnectNetWork = await isConnected();
  101. if (!isConnectNetWork) {
  102. // 无网络连接,设置友好的错误消息
  103. err.error = AppException(message: "当前网络不可用,请检查您的网络");
  104. return handler.next(err);
  105. } else if (err.error is SocketException || err.type == DioErrorType.other) {
  106. if (_retryCount < _backupUrls.length) {
  107. // 有网络连接但请求失败,尝试使用备用地址
  108. err.requestOptions.baseUrl = _backupUrls[_retryCount];
  109. try {
  110. final Response response = await _dio.fetch(err.requestOptions);
  111. return handler.resolve(response);
  112. } catch (e) {
  113. if (e is DioError) {
  114. _retryCount++;
  115. return onError(e, handler); // Recursive call
  116. } else {
  117. // Handle other exceptions if needed or rethrow them
  118. rethrow;
  119. }
  120. }
  121. }
  122. }
  123. // 其他错误,统一处理
  124. AppException appException = AppException.create(err);
  125. debugPrint('DioError===: ${appException.toString()}');
  126. err.error = appException;
  127. return handler.next(err);
  128. }
  129. }
  130. class AppException implements Exception {
  131. final int? statusCode; // 添加了 statusCode
  132. final String message;
  133. AppException({required this.message,this.statusCode});
  134. static AppException create(DioError err) {
  135. switch (err.type) {
  136. case DioErrorType.cancel:
  137. return AppException(message: '请求被取消');
  138. case DioErrorType.connectTimeout:
  139. return AppException(message: '连接超时');
  140. case DioErrorType.sendTimeout:
  141. return AppException(message: '请求超时');
  142. case DioErrorType.receiveTimeout:
  143. return AppException(message: '响应超时');
  144. case DioErrorType.response:
  145. return AppException(
  146. message: '服务器返回异常,状态码:${err.response?.statusCode}',
  147. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  148. );
  149. case DioErrorType.other:
  150. return AppException(
  151. message: '未知错误: ${err.message}',
  152. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  153. );
  154. default:
  155. return AppException(
  156. message: err.message,
  157. statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
  158. );
  159. }
  160. }
  161. @override
  162. String toString() {
  163. return message;
  164. }
  165. }
  166. extension DioClientExtension on DioClient {
  167. Future<dynamic> get(String path, {Map<String, dynamic>? queryParameters}) async {
  168. final response = await _dio.get(path, queryParameters: queryParameters);
  169. return _handleResponse(response);
  170. }
  171. Future<dynamic> post(String path, {Map<String, dynamic>? data}) async {
  172. final response = await _dio.post(path, data: data);
  173. return _handleResponse(response);
  174. }
  175. Future<dynamic> put(String path, {Map<String, dynamic>? data}) async {
  176. final response = await _dio.put(path, data: data);
  177. return _handleResponse(response);
  178. }
  179. Future<void> download(String urlPath, String savePath) async {
  180. await _dio.download(urlPath, savePath);
  181. }
  182. dynamic _handleResponse(Response response) {
  183. if (response.data is List) {
  184. return response.data as List<dynamic>;
  185. } else if (response.data is Map) {
  186. return response.data as Map<String, dynamic>;
  187. } else {
  188. throw Exception('Unsupported data type');
  189. }
  190. }
  191. }