flutter/lib/service/http_config.dart
2025-07-21 15:46:30 +08:00

73 lines
2.3 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
class HttpConfig {
static final Dio dio = Dio(BaseOptions(
// baseUrl: 'http://43.143.227.203:8099',
baseUrl: 'http://111.62.22.190:8080',
// baseUrl: 'http://cjh.wuzhongjie.com.cn',
connectTimeout: Duration(seconds: 30),
receiveTimeout: Duration(seconds: 30),
));
static final box = GetStorage();
static void init() {
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
// Token
String? token = box.read('token');
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
// Content-Type 动态处理(默认 json
if (options.extra['contentType'] != null) {
options.headers['Content-Type'] = options.extra['contentType'];
} else {
options.headers['Content-Type'] = 'application/json';
}
handler.next(options);
},
onResponse: (response, handler) {
final data = response.data;
// data['code'] = 200; // 旧接口测试用
if (data is Map<String, dynamic>) {
if (data['code'] != 200) {
Get.snackbar(
'错误',
data['msg'] ?? '请求失败',
backgroundColor: Colors.red.withAlpha(230),
colorText: Colors.white,
icon: const Icon(Icons.error_outline, color: Colors.white),
);
return handler.reject(
DioException(
requestOptions: response.requestOptions,
error: data['msg'],
response: response,
),
);
}
}
handler.next(response);
},
onError: (e, handler) {
// 网络异常处理
Get.snackbar(
'网络异常',
e.message ?? '未知错误',
backgroundColor: Colors.red.withAlpha(230),
colorText: Colors.white,
icon: const Icon(Icons.error_outline, color: Colors.white),
);
handler.next(e);
},
),
);
}
}