123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- import 'dart:convert';
- import 'dart:io';
- import 'package:connectivity_plus/connectivity_plus.dart';
- import 'package:dio/dio.dart';
- import 'package:flutter/cupertino.dart';
- import 'package:logger/logger.dart';
- import 'package:naiyouwl/app/common/LogHelper.dart';
- import '../common/SharedPreferencesUtil.dart';
- //import 'custom_interceptors.dart';
- class DioClient {
- static final DioClient _instance = DioClient._internal();
- late Dio _dio;
- factory DioClient() => _instance;
- final Logger _logger = Logger();
- DioClient._internal() {
- _dio = Dio(BaseOptions(
- baseUrl: 'https://api.androidrj01.top', // 你的API地址
- connectTimeout: 5000,
- receiveTimeout: 3000,
- ));
- // // 仅在调试模式下添加日志拦截器
- // assert(() {
- // _dio.interceptors.add(LogInterceptor(
- // request: true,
- // requestBody: true,
- // responseBody: true,
- // error: true,
- // logPrint: _logger.d, // 使用 Logger 插件打印日志
- // ));
- // return true;
- // }());
- final customInterceptor = CustomInterceptors(_dio);
- //token
- _dio.interceptors.add(TokenInterceptor());
- // 添加拦截器
- _dio.interceptors.add(customInterceptor);
- // 添加响应拦截器
- _dio.interceptors.add(InterceptorsWrapper(
- onResponse: (Response<dynamic> response, ResponseInterceptorHandler handler) async {
- final responseData = response.data as Map<String, dynamic>;
- LogHelper().d("当前地址:==== ${response.requestOptions.baseUrl} ---- $responseData");
- await SharedPreferencesUtil().setString("last_successful_url", response.requestOptions.baseUrl);
- if (responseData['ret'] == 1) {
- customInterceptor.resetRetryCount(); // 当请求成功时重置重试计数器
- handler.next(
- Response<dynamic>(
- data: responseData['data'],
- headers: response.headers,
- requestOptions: response.requestOptions,
- statusCode: response.statusCode,
- ),
- );
- } else {
- handler.reject(
- DioError(
- requestOptions: response.requestOptions,
- error: AppException(message: responseData['msg'] ?? 'Unknown Error',statusCode: responseData['ret'] ?? -1),
- ),
- );
- }
- },
- ));
- }
- void updateBaseUrl(String newBaseUrl) {
- _dio.options.baseUrl = newBaseUrl;
- }
- Dio get dio => _dio;
- }
- class TokenInterceptor extends Interceptor {
- // 这里假设您有一个方法来从安全存储中获取Token
- Future<String?> getToken() async {
- // 从您存储Token的地方获取Token,例如从SharedPreferences或SecureStorage
- String? token = await SharedPreferencesUtil().getString("token");
- return token;
- //return "Your_Token";
- }
- @override
- Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
- final token = await getToken();
- if (token != null) {
- options.headers["Authorization"] = "Bearer $token";
- }
- return super.onRequest(options, handler);
- }
- }
- class CustomInterceptors extends Interceptor {
- int _retryCount = 0;
- 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'];
- final Dio _dio; // 添加 Dio 作为参数
- CustomInterceptors(this._dio);
- Future<bool> isConnected() async {
- var connectivityResult = await (Connectivity().checkConnectivity());
- return connectivityResult != ConnectivityResult.none;
- }
- void resetRetryCount() {
- _retryCount = 0;
- }
- @override
- Future<void> onError(DioError err, ErrorInterceptorHandler handler) async {
- LogHelper().d("onError === $_retryCount");
- // 检查网络连接状态
- bool isConnectNetWork = await isConnected();
- if (!isConnectNetWork) {
- // 无网络连接,设置友好的错误消息
- err.error = AppException(message: "当前网络不可用,请检查您的网络");
- return handler.next(err);
- } else if (err.error is SocketException || err.type == DioErrorType.other || err.type == DioErrorType.connectTimeout || err.type == DioErrorType.sendTimeout || err.type == DioErrorType.receiveTimeout) {
- LogHelper().d("错误类型:==== ${err.type}");
- if (_retryCount < _backupUrls.length) {
- // 有网络连接但请求失败,尝试使用备用地址
- err.requestOptions.baseUrl = _backupUrls[_retryCount];
- LogHelper().d("切换地址:==== ${err.requestOptions.baseUrl}");
- _retryCount++;
- try {
- final Response response = await _dio.fetch(err.requestOptions);
- return handler.resolve(response);
- } catch (e) {
- if (e is DioError) {
- return onError(e, handler); // Recursive call
- } else {
- // Handle other exceptions if needed or rethrow them
- rethrow;
- }
- }
- }
- }
- // 其他错误,统一处理
- AppException appException = AppException.create(err);
- debugPrint('DioError===: ${appException.toString()}');
- err.error = appException;
- return handler.next(err);
- }
- }
- class AppException implements Exception {
- final int? statusCode; // 添加了 statusCode
- final String message;
- AppException({required this.message,this.statusCode});
- static AppException create(DioError err) {
- switch (err.type) {
- case DioErrorType.cancel:
- return AppException(message: '请求被取消');
- case DioErrorType.connectTimeout:
- return AppException(message: '连接超时');
- case DioErrorType.sendTimeout:
- return AppException(message: '请求超时');
- case DioErrorType.receiveTimeout:
- return AppException(message: '响应超时');
- case DioErrorType.response:
- return AppException(
- message: '服务器返回异常,状态码:${err.response?.statusCode}',
- statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
- );
- case DioErrorType.other:
- return AppException(
- message: '网络连接失败',
- statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
- );
- default:
- return AppException(
- message: err.message,
- statusCode: err.response?.statusCode, // 设置statusCode,即使在default中也可以选择设置
- );
- }
- }
- @override
- String toString() {
- return message;
- }
- }
- extension DioClientExtension on DioClient {
- Future<dynamic> get(String path, {Map<String, dynamic>? queryParameters}) async {
- final response = await _dio.get(path, queryParameters: queryParameters);
- return _handleResponse(response);
- }
- Future<dynamic> post(String path, {Map<String, dynamic>? data}) async {
- final response = await _dio.post(path, data: data);
- return _handleResponse(response);
- }
- Future<dynamic> put(String path, {Map<String, dynamic>? data}) async {
- final response = await _dio.put(path, data: data);
- return _handleResponse(response);
- }
- Future<void> download(String urlPath, String savePath) async {
- await _dio.download(urlPath, savePath);
- }
- dynamic _handleResponse(Response response) {
- if (response.data is List) {
- return response.data as List<dynamic>;
- } else if (response.data is Map) {
- return response.data as Map<String, dynamic>;
- } else {
- throw Exception('Unsupported data type');
- }
- }
- }
|