import "package:dio/dio.dart";
import 'dart:async';
/*
* 封装 restful 请求*
* GET、POST、DELETE、PATCH
* 主要作用为统一处理相关事务: * - 统一处理请求前缀; * - 统一打印请求信息; * - 统一打印响应信息; * - 统一打印报错信息;*/
class ones {
/// global dio object
static Diodio;
/// default options
static const StringAPI_PREFIX ='https://4edca071-2241-4231-b060-6cf2201bf7b4.mock.pstmn.io/xzj';
static const intCONNECT_TIMEOUT =5000;
static const intRECEIVE_TIMEOUT =2000;
/// http request methods
static const StringGET ='get';
static const StringPOST ='post';
static const StringPUT ='put';
static const StringPATCH ='patch';
static const StringDELETE ='delete';
/// request method
static Futurerequest (
String url,
{ data, method })async {
data = data ?? {};
method = method ??'GET';
/// 打印请求相关信息:请求地址、请求方式、请求参数
print('请求地址:【' + method +' ' + url +'】');
print('请求参数:' + data.toString());
Dio dio =createInstance();
var result;
try {
print("url:"+url);
Response response =await dio.request(url, queryParameters: data, options:new Options(method: method));
result = response.data;
/// 打印响应相关信息
print('响应数据:' + response.toString());
}on DioErrorcatch (e) {
/// 打印请求失败相关信息
print('请求出错:' + e.toString());
}
return result.toString();
}
/// 创建 dio 实例对象
static DiocreateInstance () {
if (dio ==null) {
/// 全局属性:请求前缀、连接超时时间、响应超时时间
BaseOptions options =new BaseOptions(
baseUrl:API_PREFIX,
connectTimeout:CONNECT_TIMEOUT,
receiveTimeout:RECEIVE_TIMEOUT,
);
dio =new Dio(options);
}
return dio;
}
/// 清空 dio 对象
static clear () {
dio =null;
}
}