This commit is contained in:
2026-11-08 14:30:16 +08:00
parent 14ae9d6414
commit 6ffa548b25
2 changed files with 50 additions and 31 deletions
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 生产环境全部走 HTTPS;仅放行开发用局域网/模拟器地址 -->
<!-- HTTPS 主域名 + 明文降级通道与开发用局域网/模拟器地址 -->
<network-security-config>
<base-config cleartextTrafficPermitted="false" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">ceryuan.top</domain>
<domain includeSubdomains="false">42.194.179.190</domain>
<domain includeSubdomains="false">192.168.31.68</domain>
<domain includeSubdomains="false">10.0.2.2</domain>
+48 -30
View File
@@ -1,5 +1,6 @@
/// dio 封装:baseUrl(--dart-define 可配)、token 注入、统一错误、401 处理。
/// 连接类失败(3003 端口被运营商/网络拦截)自动改走 80 端口并记忆,无需重装。
/// 候选地址依次切换:HTTPS 证书异常/连接失败 → 自动降级明文域名 → 旧 IP:3003,
/// 成功后记忆,无需重装。
library;
import 'package:dio/dio.dart';
@@ -13,10 +14,16 @@ import 'api_error.dart';
const kDefaultBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://42.194.179.190:3003', // 正式端
defaultValue: 'https://ceryuan.top', // 正式端(HTTPS 域名)
);
/// 当前生效的服务器地址(连接失败自动换端口后会更新)
/// 候选地址按序尝试;连接失败或证书异常时切换到下一个
const kBaseUrlCandidates = <String>[
'https://ceryuan.top',
'http://42.194.179.190:3003', // 旧直连兜底(WiFi 下可用)
];
/// 当前生效的服务器地址(切换成功后会更新)
final ValueNotifier<String> activeBaseUrl = ValueNotifier(kDefaultBaseUrl);
class ApiClient {
@@ -32,10 +39,13 @@ class ApiClient {
headers: {'Content-Type': 'application/json'},
),
);
// 恢复上次记下的可用地址(比如 80 端口)
// 恢复上次记下的可用地址
SharedPreferences.getInstance().then((p) {
final saved = p.getString(_kBasePref);
if (saved != null && saved.isNotEmpty && saved != _dio.options.baseUrl) {
if (saved != null &&
saved.isNotEmpty &&
kBaseUrlCandidates.contains(saved) &&
saved != _dio.options.baseUrl) {
_dio.options.baseUrl = saved;
activeBaseUrl.value = saved;
}
@@ -57,8 +67,8 @@ class ApiClient {
handler.next(r);
},
onError: (e, handler) {
// 连接类失败保留原始类型,交给 _send 做端口切换重试
if (_isConnError(e)) {
// 连接/证书类失败保留原始类型,交给 _send 做候选切换
if (_isSwitchable(e)) {
DebugLogger.instance.log('ERR', '${e.type.name} ${e.requestOptions.uri}');
handler.next(e);
return;
@@ -74,24 +84,22 @@ class ApiClient {
);
}
static const _kBasePref = 'xl_api_base';
static const _kBasePref = 'xl_api_base_v2'; // v2:旧 IP 端口记忆不迁移
final TokenStore _tokens;
late final Dio _dio;
Dio get dio => _dio;
String get baseUrl => _dio.options.baseUrl;
static bool _isConnError(DioException e) =>
/// 连接失败 / 证书异常 / 服务端 5xx(可能后端在重启)→ 尝试下一候选
static bool _isSwitchable(DioException e) =>
e.type == DioExceptionType.connectionTimeout ||
e.type == DioExceptionType.connectionError;
/// 3003 → 80(运营商几乎不封 80);其余端口不切换
static String? _alternateUrl(String url) {
final u = Uri.parse(url);
if (u.port != 3003) return null;
final s = u.replace(port: 80).toString();
return s.endsWith(':80') ? s.substring(0, s.length - 3) : s;
}
e.type == DioExceptionType.connectionError ||
e.type == DioExceptionType.badCertificate ||
(e.type == DioExceptionType.unknown &&
(e.error?.toString().contains('HandshakeException') ?? false)) ||
(e.type == DioExceptionType.badResponse &&
(e.response?.statusCode ?? 0) >= 500);
Future<void> _rememberBase(String url) async {
activeBaseUrl.value = url;
@@ -118,9 +126,12 @@ class ApiClient {
if (status == 401) {
return ApiError(1009, '登录已失效,请重新登录', httpStatus: 401);
}
if (_isConnError(e) || e.type == DioExceptionType.receiveTimeout) {
if (_isSwitchable(e) || e.type == DioExceptionType.receiveTimeout) {
return ApiError(9002, '网络异常,请检查网络后重试');
}
if (e.type == DioExceptionType.badCertificate) {
return ApiError(9003, '服务器证书异常,请稍后重试');
}
return ApiError(5000, '服务暂不可用,请稍后重试', httpStatus: status);
}
@@ -139,20 +150,27 @@ class ApiClient {
Future<Map<String, dynamic>> delete(String path, {Object? body}) =>
_run(() => _dio.delete(path, data: body));
/// 发送 + 连接失败自动换 80 端口重试一次
/// 发送;可切换类失败时按候选列表逐个重试,成功即记忆
Future<Response> _send(Future<Response> Function() f) async {
try {
final r = await f();
return r;
return await f();
} on DioException catch (e) {
if (!_isConnError(e)) rethrow;
final alt = _alternateUrl(baseUrl);
if (alt == null) rethrow;
DebugLogger.instance.log('REQ', '换用 $alt 重试');
_dio.options.baseUrl = alt;
final r = await f();
await _rememberBase(alt); // 换端口成功并记忆
return r;
if (!_isSwitchable(e)) rethrow;
final tried = <String>{_dio.options.baseUrl};
for (final cand in kBaseUrlCandidates) {
if (tried.contains(cand)) continue;
tried.add(cand);
DebugLogger.instance.log('REQ', '切换候选 $cand 重试');
_dio.options.baseUrl = cand;
try {
final r = await f();
await _rememberBase(cand);
return r;
} on DioException catch (e2) {
if (!_isSwitchable(e2)) rethrow;
}
}
rethrow;
}
}