dio_client.dart 7.4 KB

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