dio_utils.dart
4.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/**
* dio_utils.dart
*
* Created by iotjin on 2020/07/06.
* description: dio 工具类
*/
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_mes2/bean/LoginrResult.dart';
import 'package:flutter_mes2/utils/Constant.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'apis.dart';
import 'log_utils.dart';
import 'error_handle.dart';
const int _connectTimeout = 30 * 1000;
const int _receiveTimeout = 30 * 1000;
const int _sendTimeout = 30 * 1000;
typedef Success<T> = Function(T data);
typedef Fail = Function(int code, String msg);
//typedef SuccessListCallback<T> = Function(List<T> data);
class DioUtils {
// default options
static String TOKEN = '';
static String COOKIE = '';
static String network = null;
List<Cookie> cookies = [
new Cookie("xxx", "12"),
// ....
];
static Dio _dio;
// 创建 dio 实例对象
static Dio createInstance() {
if(network == null) {
network = Constant.DEFAULT_NETWORK;
}
// if (_dio == null) {
/// 全局属性:请求前缀、连接超时时间、响应超时时间
var options = BaseOptions(
/// 请求的Content-Type,默认值是"application/json; charset=utf-8".
/// 如果您想以"application/x-www-form-urlencoded"格式编码请求数据,
/// 可以设置此选项为 `Headers.formUrlEncodedContentType`, 这样[Dio]就会自动编码请求体.
// contentType: Headers.formUrlEncodedContentType, // 适用于post form表单提交
responseType: ResponseType.json,
validateStatus: (status) {
// 不使用http状态码判断状态,使用AdapterInterceptor来处理(适用于标准REST风格)
return true;
},
baseUrl: network,
headers: httpHeaders,
connectTimeout: _connectTimeout,
receiveTimeout: _receiveTimeout,
sendTimeout: _sendTimeout,
);
_dio = new Dio(options);
// }
_dio.options.headers['access-token'] = TOKEN;
return _dio;
}
// 清空 dio 对象
static clear() {
_dio = null;
}
// 请求,返回参数为 T
// method:请求方法,Method.POST等
// path:请求地址
// params:请求参数
// success:请求成功回调
// error:请求失败回调
static Future request<T>(Method method, String path, dynamic params,
{Success success, Fail fail}) async {
try {
Dio _dio = createInstance();
// _dio.interceptors.add(CookieManager(cookies));
Response response = await _dio.request(path,
data: params, options: Options(method: MethodValues[method]));
if (response != null) {
if(response.statusCode == 404) {
_onError(ExceptionHandle.unknown_error, '请求的接口不存在', fail);
return;
}
if (success != null) {
success(response.data);
}
} else {
_onError(ExceptionHandle.unknown_error, '未知错误', fail);
}
} on DioError catch (e) {
final NetError netError = ExceptionHandle.handleException(e);
_onError(netError.code, netError.msg, fail);
}
}
// //Post请求
// static Future post<T>(
// String url, {
// parameters,
// Function(T) success,
// Function(String error) fail,
// }) async {
// //请求参数
// parameters = parameters ?? {};
// //参数处理
//// LogUtils.d("--------- parameters ---------");
//// LogUtils.d("$parameters");
// try {
// Response response;
// Dio dio = createInstance();
// response = await dio.post(url, data: parameters);
//// LogUtils.d("--------- response ---------");
//// LogUtils.d('$response');
//// LogUtils.print_(response.toString());
// var responseData = response.data;
// if (responseData['code'] == 200) {
// if (success != null) {
// success(responseData['data']);
// }
// } else {
// throw Exception('erroMsg:${responseData['msg']}');
// }
// } catch (e) {
// LogUtils.d('请求出错:' + e.toString());
// fail(e.toString());
// }
// }
}
/// 自定义Header
Map<String, dynamic> httpHeaders = {
'Accept': 'application/json,*/*',
'Content-Type': 'application/json',
'access-token': DioUtils.TOKEN,
'Cookie': DioUtils.COOKIE
};
void _onError(int code, String msg, Fail fail) {
if (code == null) {
code = ExceptionHandle.unknown_error;
msg = '未知异常';
}
LogUtils.print_('接口请求异常: code: $code, msg: $msg');
if (fail != null) {
fail(code, msg);
}
}
Map<String, dynamic> parseData(String data) {
return json.decode(data) as Map<String, dynamic>;
}
enum Method { GET, POST, DELETE, PUT, PATCH, HEAD }
//使用:MethodValues[Method.POST]
const MethodValues = {
Method.GET: "get",
Method.POST: "post",
Method.DELETE: "delete",
Method.PUT: "put",
Method.PATCH: "patch",
Method.HEAD: "head",
};