1.定义请求方式枚举
// http_method.dart
class HttpMethod{
static const String GET = "GET";
static const String POST = "POST";
static const String PUT = "PUT";
static const String DELETE = "DELETE";
static const String HEAD = "HEAD";
static const String PATCH = "PATCH";
static const String OPTIONS = "OPTIONS";
static const String TRACE = "TRACE";
static const String CONNECT = "CONNECT";
static const String ALL = "ALL";
}
2.添加请求拦截器
//print_log_interceptor.dart
import 'package:dio/dio.dart';
class PrintLogInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
print("请求url:${options.uri}");
print("请求参数:${options.queryParameters}");
print("请求头:${options.headers}");
print("请求数据:${options.data}");
return super.onRequest(options, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
print("响应数据:${response.data}");
return super.onResponse(response, handler);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
print("错误信息:${err.error}");
return super.onError(err, handler);
}
}
2.对Dio进行封装
class DioInstance {
static DioInstance? _instance;
DioInstance._();
static DioInstance instance() {
return _instance ??= DioInstance._();
}
final Dio _dio = Dio();
final _defaultTime = const Duration(seconds: 30);
void initDio({
required String baseUrl,
String? httpMethod = HttpMethod.GET,
Duration? connectTimeout,
Duration? receiveTimeout,
Duration? sendTimeout,
ResponseType? responseType,
String? contentType,
}) {
_dio.options = BaseOptions(
method: httpMethod,
baseUrl: baseUrl,
connectTimeout: connectTimeout ?? _defaultTime,
receiveTimeout: receiveTimeout ?? _defaultTime,
sendTimeout: sendTimeout ?? _defaultTime,
responseType: responseType ?? ResponseType.json,
contentType: contentType,
);
_dio.interceptors.add(PrintLogInterceptor());
}
// get 请求
Future<Response> get({
required String path,
Map<String, dynamic>? param,
Options? options,
CancelToken? cancelToken,
}) async {
return await _dio.get(
path,
queryParameters: param,
options: options ??
Options(
method: HttpMethod.GET,
receiveTimeout: _defaultTime,
sendTimeout: _defaultTime,
),
cancelToken: cancelToken,
);
}
// post请求
Future<Response> post({
required String path,
Object? data,
Map<String, dynamic>? queryParameters,
Options? options,
CancelToken? cancelToken,
}) async {
return await _dio.post(
path,
data: data,
queryParameters: queryParameters,
options: options ??
Options(
method: HttpMethod.POST,
receiveTimeout: _defaultTime,
sendTimeout: _defaultTime,
),
cancelToken: cancelToken,
);
}
}