Files
flutter-jdt-store/lib/utils/request.dart
2023-12-22 23:27:14 +08:00

86 lines
2.6 KiB
Dart

import 'package:dio/dio.dart';
import 'package:flutter_jdt_store/utils/utils.dart';
class Request {
// 构造函数
Request() {
init();
}
static final Dio _dio = Dio();
static void init() {
// 基本配置
_dio.options.baseUrl =
"https://www.wanzhuanyongcheng.cn/app"; // 替换为你的 API 地址
_dio.options.connectTimeout = const Duration(seconds: 15); // 连接超时时间,单位是毫秒
_dio.options.receiveTimeout = const Duration(seconds: 15); // 接收超时时间,单位是毫秒
_dio.options.headers["Content-Type"] = "application/json; charset=utf-8";
_dio.options.headers["token"] = StorageUtil().getString("token");
// 添加请求拦截器
_dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
// 在请求被发送之前做一些事情
return handler.next(options); // 必须返回 options
},
));
// 添加响应拦截器
_dio.interceptors.add(InterceptorsWrapper(
onResponse: (response, handler) {
// 在响应被处理之前做一些事情
final Map<String, dynamic> data = response.data;
// 状态码不等于200时抛出异常
if (data["code"] != 200) {
ToolFn.tips(data["msg"].toString());
throw DioException(
requestOptions: response.requestOptions,
response: response,
error: data["msg"],
);
}
return handler.next(response); // 必须返回 response
},
onError: (DioException e, handler) {
// 在响应错误被处理之前做一些事情
return handler.next(e); // 必须返回 error
},
));
}
static Future<T> get<T>(String path, {Map<String, dynamic>? params}) async {
try {
final Response<T> response =
await _dio.get<T>(path, queryParameters: params);
return response.data!;
} catch (error) {
throw _handleError(error);
}
}
static Future<T> post<T>(String path, {Map<String, dynamic>? data}) async {
try {
final Response<T> response = await _dio.post<T>(path, data: data);
return response.data!;
} catch (error) {
throw _handleError(error);
}
}
// 处理错误
static Exception _handleError(error) {
if (error is DioException) {
String message = "网络请求失败";
if (error.response != null && error.response!.data != null) {
message = error.response!.data.toString();
}
return Exception(message);
} else {
return Exception("未知错误");
}
}
}