基础库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

372 lines
11 KiB

  1. import 'package:dio/dio.dart';
  2. import 'package:dio/adapter.dart';
  3. import 'package:zhiying_comm/util/empty_util.dart';
  4. import 'dart:io';
  5. import 'dart:ui';
  6. import 'dart:convert';
  7. import 'package:zhiying_comm/zhiying_comm.dart';
  8. import 'package:package_info/package_info.dart';
  9. import 'package:device_info/device_info.dart';
  10. import 'package:fluttertoast/fluttertoast.dart';
  11. import 'global_config.dart';
  12. import 'shared_prefe_util.dart';
  13. import 'time_util.dart';
  14. typedef OnSuccess = dynamic Function(dynamic data);
  15. typedef OnError = dynamic Function(String e);
  16. typedef OnCache = dynamic Function(dynamic data);
  17. enum NetMethod {
  18. GET,
  19. POST,
  20. PUT,
  21. DELETE,
  22. OPTIONS,
  23. PATCH,
  24. UPDATE,
  25. HEAD,
  26. }
  27. class NetUtil {
  28. Dio _dio;
  29. NetUtil._();
  30. static NetUtil _instance;
  31. static NetUtil getInstance() {
  32. if (_instance == null) {
  33. _instance = NetUtil._();
  34. }
  35. return _instance;
  36. }
  37. get dio async {
  38. if (_dio == null) {
  39. var setting = await NativeUtil.getSetting();
  40. String domain = setting['domain']; //'http://www.hairuyi.com/';
  41. _config(domain, proxyUrl: '192.168.0.112:8888');
  42. }
  43. return _dio;
  44. }
  45. /// 配置网络请求,基础地址,代理地址,如:192.168.0.123:8888(代理地址生产环境无效)
  46. /// apiVersion 接口版本
  47. void _config(String baseUrl, {String proxyUrl}) {
  48. _dio = Dio(BaseOptions(
  49. method: "post",
  50. baseUrl: baseUrl,
  51. connectTimeout: 15000,
  52. receiveTimeout: 15000,
  53. contentType: Headers.jsonContentType,
  54. followRedirects: true,
  55. headers: {'device': 'wx_applet', 'Platform': 'wx_applet'},
  56. ));
  57. _dio.interceptors.add(_NetInterceptors());
  58. _dio.interceptors.add(LogInterceptor());
  59. const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  60. if (proxyUrl != null && proxyUrl != '' && !inProduction) {
  61. _setProxy(proxyUrl);
  62. }
  63. }
  64. /// 设置代理
  65. void _setProxy(String proxyUrl) {
  66. (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
  67. (HttpClient client) {
  68. client.findProxy = (uri) {
  69. return "PROXY $proxyUrl";
  70. };
  71. client.badCertificateCallback =
  72. (X509Certificate cert, String host, int port) => true;
  73. };
  74. }
  75. /// 同步请求
  76. static Future<dynamic> post(String path,
  77. {Map<String, dynamic> params}) async {
  78. if (params == null) {
  79. params = {};
  80. }
  81. Map<String, dynamic> sign = await signParams(params);
  82. Response response;
  83. try {
  84. Dio dio = await NetUtil.getInstance().dio;
  85. response = await dio.post(path, data: sign);
  86. } on DioError catch (e) {
  87. _formatError(e);
  88. // Logger.error(e);
  89. }
  90. if (response == null) {
  91. return null;
  92. }
  93. if (response.statusCode != 200) {
  94. // 请求错误
  95. const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  96. if (!inProduction) {
  97. Fluttertoast.showToast(msg: response.statusMessage);
  98. }
  99. // log.e(response.statusMessage);
  100. return null;
  101. }
  102. var result = response.data;
  103. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
  104. GlobalConfig.RESPONSE_SUCCESS_CODE ||
  105. result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
  106. '${GlobalConfig.RESPONSE_SUCCESS_CODE}') {
  107. Logger.error(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]);
  108. Fluttertoast.showToast(
  109. msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
  110. toastLength: Toast.LENGTH_SHORT,
  111. gravity: ToastGravity.BOTTOM,
  112. );
  113. }
  114. return result;
  115. }
  116. /// 异步请求
  117. static void request(String path,
  118. {NetMethod method = NetMethod.GET,
  119. Map<String, dynamic> params,
  120. Map<String, File> multiFiles,
  121. OnSuccess onSuccess,
  122. OnError onError,
  123. OnCache onCache}) async {
  124. if (params == null) {
  125. params = {};
  126. }
  127. // 根据请求参数,获取缓存的Key
  128. String cacheKey = _getRequestParamsCachedKey(params, path);
  129. // // 读取缓存回调
  130. if (onCache != null) {
  131. await _onCallBackCacheData(onCache, cacheKey);
  132. }
  133. // 参数签名
  134. Map<String, dynamic> sign = await signParams(params);
  135. Response response;
  136. try {
  137. Dio dio = await NetUtil.getInstance().dio;
  138. response = await dio.request(path,
  139. data: sign, options: Options(method: enumToString(method)));
  140. } on DioError catch (e) {
  141. _formatError(e);
  142. }
  143. try {
  144. var result =
  145. response.data is Map ? response.data : jsonDecode(response.data);
  146. // TODO 解密?
  147. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
  148. GlobalConfig.RESPONSE_SUCCESS_CODE ||
  149. result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
  150. '${GlobalConfig.RESPONSE_SUCCESS_CODE}') {
  151. if (onSuccess != null) {
  152. onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
  153. // 缓存返回的数据
  154. _setCallBackCacheData(cacheKey,
  155. response.data is Map ? jsonEncode(response.data) : response.data);
  156. }
  157. return;
  158. }
  159. Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]);
  160. Fluttertoast.showToast(
  161. msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
  162. toastLength: Toast.LENGTH_SHORT,
  163. gravity: ToastGravity.BOTTOM,
  164. );
  165. if (onError != null) {
  166. onError(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG] ?? '未知错误');
  167. }
  168. } catch (e) {
  169. if (onError != null) {
  170. onError(e?.toString() ?? '未知错误');
  171. }
  172. }
  173. return;
  174. }
  175. /// 统一添加必要的参数
  176. static Future<Map<String, dynamic>> signParams(
  177. Map<String, dynamic> params) async {
  178. // 应用信息
  179. PackageInfo packageInfo = await PackageInfo.fromPlatform();
  180. // 原生传的信息
  181. Map setting = await NativeUtil.getSetting();
  182. if (Platform.isIOS) {
  183. IosDeviceInfo iosInfo = await DeviceInfoPlugin().iosInfo;
  184. // 设备
  185. params["platform"] = "ios";
  186. // 设备系统版本
  187. params["system_version"] = iosInfo?.systemVersion;
  188. // 设备型号 如:iPhone 11pro
  189. params['device_model'] = iosInfo?.name;
  190. // 设备型号,如:MLMF2LL/A
  191. // params['device_number'] = iosInfo?.model;
  192. // 设备ID
  193. params['device_id'] = iosInfo?.identifierForVendor;
  194. } else if (Platform.isAndroid) {
  195. AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
  196. // 设备
  197. params["platform"] = "android";
  198. // 设备系统版本
  199. params["system_version"] = "Android ${androidInfo?.version?.release}";
  200. // 设备型号 如:iPhone 11pro
  201. params['device_model'] = androidInfo?.model;
  202. // 设备型号,如:MLMF2LL/A
  203. // params['device_number'] = androidInfo?.id;
  204. // 设备Id
  205. params['device_id'] = androidInfo?.androidId;
  206. }
  207. // 应用版本号
  208. params["app_version"] = packageInfo.version;
  209. // 分辨率
  210. params["solution"] =
  211. "${window.physicalSize.width.floor()}*${window.physicalSize.height.floor()}";
  212. // 站长ID
  213. String masterId = setting['master_id'];
  214. if (null != null &&
  215. masterId != '' &&
  216. (!params.containsKey('master_id') || params['master_id'] == '')) {
  217. params['master_id'] = masterId;
  218. }
  219. // secret_key
  220. params['secret_key'] = setting['secret_key'];
  221. // token
  222. String token = setting['token'];
  223. if (token != null &&
  224. token != '' &&
  225. (!params.containsKey('token') || params['token'] == '')) {
  226. params['token'] = token;
  227. }
  228. // 当前时间戳:秒
  229. params["time"] = TimeUtil.getNowTime();
  230. // 过滤空字段,过滤首尾空格
  231. Map<String, dynamic> filters = Map<String, dynamic>();
  232. params.forEach((key, value) {
  233. if (key != '' && value != '') {
  234. filters[key] = (value is String) ? value.trim() : value;
  235. }
  236. });
  237. params = filters;
  238. List<String> list = List<String>();
  239. params.forEach((key, value) {
  240. list.add(key.toString() + value.toString());
  241. });
  242. params["sign"] = signWithArray(list);
  243. return params;
  244. }
  245. /// 获取请求缓存成功的数据
  246. static Future<void> _onCallBackCacheData(
  247. OnCache onCache, String cacheKey) async {
  248. // 读取缓存
  249. Map<String, dynamic> cacheMap =
  250. await SharedPreferencesUtil.getNetCacheResult(cacheKey);
  251. if (!EmptyUtil.isEmpty(cacheMap) &&
  252. cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
  253. (cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
  254. GlobalConfig.RESPONSE_SUCCESS_CODE ||
  255. cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
  256. '${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
  257. null != cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]) {
  258. onCache(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
  259. return;
  260. }
  261. return;
  262. }
  263. /// 缓存请求成功的数据
  264. static void _setCallBackCacheData(String cacheKey, String value) async {
  265. SharedPreferencesUtil.setNetCacheResult(cacheKey, value);
  266. }
  267. /// 根据请求参数,获取缓存的Key
  268. static String _getRequestParamsCachedKey(
  269. Map<String, dynamic> map, String path) {
  270. if (EmptyUtil.isEmpty(map)) {
  271. return EncodeUtil.generateMd5(path);
  272. }
  273. return EncodeUtil.generateMd5(path + map.toString());
  274. }
  275. /// 签名
  276. static String signWithArray(List<String> params) {
  277. // 字母升序
  278. params.sort();
  279. String result = "";
  280. // result += secret_key;
  281. params.forEach((param) {
  282. result += param;
  283. });
  284. // result += secret_key;
  285. return EncodeUtil.generateMd5(result);
  286. }
  287. /*
  288. * error统一处理
  289. */
  290. static void _formatError(DioError e) {
  291. if (e.type == DioErrorType.CONNECT_TIMEOUT) {
  292. Logger.error('连接超时: ${e.toString()}');
  293. } else if (e.type == DioErrorType.SEND_TIMEOUT) {
  294. Logger.error('请求超时: ${e.toString()}');
  295. } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
  296. Logger.error('响应超时: ${e.toString()}');
  297. } else if (e.type == DioErrorType.RESPONSE) {
  298. Logger.error('出现异常: ${e.toString()}');
  299. } else if (e.type == DioErrorType.CANCEL) {
  300. Logger.error('请求取消: ${e.toString()}');
  301. } else {
  302. Logger.error('未知错误: ${e.toString()}');
  303. }
  304. }
  305. }
  306. /**
  307. * @description: 网络请求拦截器
  308. * @param {type}
  309. * @return:
  310. */
  311. class _NetInterceptors extends InterceptorsWrapper {
  312. @override
  313. Future onRequest(RequestOptions options) {
  314. Logger.net(options?.uri?.toString(), data: options.data.toString());
  315. // TODO 加密?
  316. return super.onRequest(options);
  317. }
  318. @override
  319. Future onResponse(Response response) {
  320. Logger.endNet(response?.request?.uri?.toString(),
  321. data: response?.data?.toString() ?? '');
  322. // TODO 解密?
  323. return super.onResponse(response);
  324. }
  325. @override
  326. Future onError(DioError err) {
  327. // Logger.error(err);
  328. return super.onError(err);
  329. }
  330. }