基础库
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.
 
 
 
 
 

551 regels
18 KiB

  1. import 'dart:collection';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:ui';
  5. import 'package:device_info/device_info.dart';
  6. import 'package:dio/adapter.dart';
  7. import 'package:dio/dio.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:fluttertoast/fluttertoast.dart';
  10. import 'package:imei_plugin/imei_plugin.dart';
  11. import 'package:package_info/package_info.dart';
  12. import 'package:provider/provider.dart';
  13. import 'package:zhiying_comm/util/empty_util.dart';
  14. import 'package:zhiying_comm/zhiying_comm.dart';
  15. import 'encode_util.dart';
  16. import 'global_config.dart';
  17. import 'shared_prefe_util.dart';
  18. import 'time_util.dart';
  19. typedef OnSuccess = dynamic Function(dynamic data);
  20. typedef OnError = dynamic Function(String e);
  21. typedef OnCache = dynamic Function(dynamic data);
  22. final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
  23. enum NetMethod {
  24. GET,
  25. POST,
  26. PUT,
  27. DELETE,
  28. OPTIONS,
  29. PATCH,
  30. UPDATE,
  31. HEAD,
  32. }
  33. class NetUtil {
  34. Dio _dio;
  35. NetUtil._();
  36. static NetUtil _instance;
  37. static NetUtil getInstance() {
  38. if (_instance == null) {
  39. _instance = NetUtil._();
  40. }
  41. return _instance;
  42. }
  43. get dio async {
  44. if (_dio == null) {
  45. var setting = await NativeUtil.getSetting();
  46. String domain = setting['domain']; //'http://www.hairuyi.com/';
  47. _config(domain, proxyUrl: '192.168.0.102:8866'); // 192.168.0.66:8866
  48. }
  49. return _dio;
  50. }
  51. /// 配置网络请求,基础地址,代理地址,如:192.168.0.123:8888(代理地址生产环境无效)
  52. /// apiVersion 接口版本
  53. void _config(String baseUrl, {String proxyUrl}) {
  54. _dio = Dio(BaseOptions(
  55. method: "post",
  56. baseUrl: baseUrl,
  57. connectTimeout: 15000,
  58. receiveTimeout: 15000,
  59. contentType: Headers.jsonContentType,
  60. followRedirects: true,
  61. headers: {'device': 'wx_applet', 'Platform': 'wx_applet'},
  62. validateStatus: (_) {
  63. return true;
  64. }));
  65. _dio.interceptors.add(_NetInterceptors());
  66. // _dio.interceptors.add(LogInterceptor());
  67. const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  68. if (proxyUrl != null && proxyUrl != '' && !inProduction) {
  69. _setProxy(proxyUrl);
  70. }
  71. }
  72. /// 设置代理
  73. void _setProxy(String proxyUrl) {
  74. (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
  75. client.findProxy = (uri) {
  76. return "PROXY $proxyUrl";
  77. };
  78. client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  79. };
  80. }
  81. /// 同步请求
  82. static Future<dynamic> post(String path,
  83. {Map<String, dynamic> params, Map<String, dynamic> queryParameters, NetMethod method = NetMethod.POST, bool cache = false, bool showToast = true}) async {
  84. var paramsData = {
  85. 'postData': params ?? {},
  86. 'queryParameters': queryParameters ?? {}
  87. };
  88. // 根据请求参数,获取缓存的Key
  89. String cacheKey = getRequestParamsCachedKey(paramsData, path);
  90. // 参数签名 TODO 加密?
  91. // post请求的参数
  92. Map<String, dynamic> bodyParams = params;
  93. // 请求头参数
  94. Map<String, dynamic> headParam = await _getMustHeadParams();
  95. Response response;
  96. try {
  97. Dio dio = await NetUtil
  98. .getInstance()
  99. .dio;
  100. response = await dio.request(
  101. path,
  102. data: !EmptyUtil.isEmpty(bodyParams) ? bodyParams : null,
  103. options: Options(method: enumToString(method), headers: headParam),
  104. queryParameters: !EmptyUtil.isEmpty(queryParameters) ? queryParameters : null,
  105. );
  106. } on DioError catch (e) {
  107. _formatError(e);
  108. }
  109. try {
  110. var result = response.data is Map ? response.data : jsonDecode(response.data);
  111. // TODO 解密?
  112. if (isSuccess(result)) {
  113. // 缓存成功的数据
  114. if (cache) {
  115. _setCallBackCacheData(cacheKey, response.data is Map ? jsonEncode(response.data) : response.data);
  116. }
  117. return result;
  118. // 缓存返回的数据
  119. } else {
  120. Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]);
  121. ///
  122. /// 401000 验证用户失败(不提示Toast)
  123. /// 404004 没有找到对应模块(跳空页面,不提示toast)
  124. ///
  125. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] != 401000 && result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] != 404004) {
  126. if (showToast) {
  127. Fluttertoast.showToast(
  128. msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
  129. toastLength: Toast.LENGTH_SHORT,
  130. gravity: ToastGravity.BOTTOM,
  131. );
  132. }
  133. }
  134. ///
  135. /// 401003 用户被逼下线
  136. /// 退出登陆(清理token等用户信息)
  137. ///
  138. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '401003') {
  139. try {
  140. Future.delayed(Duration(seconds: 0)).then((onValue) {
  141. BuildContext context = navigatorKey.currentState.overlay.context;
  142. Provider.of<UserInfoNotifier>(context, listen: false).unLogin();
  143. });
  144. } catch (e, s) {
  145. Logger.error(e, s);
  146. }
  147. }
  148. ///
  149. /// 403028 账号被冻结
  150. /// 403029 账号被禁用
  151. /// 提示并且退出登录
  152. ///
  153. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '403028' || result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '403029') {
  154. try {
  155. // 提示
  156. Fluttertoast.showToast(
  157. msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
  158. toastLength: Toast.LENGTH_SHORT,
  159. gravity: ToastGravity.BOTTOM,
  160. );
  161. // 退出登录
  162. Future.delayed(Duration(seconds: 0)).then((onValue) {
  163. BuildContext context = navigatorKey.currentState.overlay.context;
  164. Provider.of<UserInfoNotifier>(context, listen: false).unLogin();
  165. });
  166. } catch (e, s) {
  167. Logger.error(e, s);
  168. }
  169. }
  170. return result;
  171. }
  172. } catch (e) {
  173. return null;
  174. }
  175. }
  176. /// 异步请求
  177. static void request(String path, {NetMethod method = NetMethod.GET, Map<String, dynamic> params, Map<String,
  178. dynamic> queryParameters, OnSuccess onSuccess, OnError onError, OnCache onCache, bool showToast = true}) async {
  179. var paramsData = {
  180. 'postData': params ?? {},
  181. 'queryParameters': queryParameters ?? {}
  182. };
  183. // 根据请求参数,获取缓存的Key
  184. String cacheKey = getRequestParamsCachedKey(paramsData, path);
  185. print("缓存Key"+cacheKey);
  186. // // 读取缓存回调
  187. if (onCache != null) {
  188. await _onCallBackCacheData(onCache, cacheKey);
  189. }
  190. try {
  191. Map result = await NetUtil.post(path, method: method,
  192. params: params,
  193. queryParameters: queryParameters,
  194. showToast: showToast,
  195. cache: onCache != null);
  196. // TODO 解密?
  197. if (isSuccess(result)) {
  198. if (onSuccess != null) {
  199. onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
  200. }
  201. return;
  202. }
  203. if (onError != null) {
  204. onError(!EmptyUtil.isEmpty(result) ? !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]) ? result[GlobalConfig.HTTP_RESPONSE_KEY_MSG] : '未知错误' : '未知错误');
  205. }
  206. } catch (e) {
  207. Logger.error('error: ' + e.toString());
  208. if (onError != null) {
  209. onError(e?.toString() ?? '未知错误');
  210. }
  211. }
  212. return;
  213. }
  214. /// 统一添加必要的参数
  215. // static Future<Map<String, dynamic>> signParams(Map<String, dynamic> params) async {
  216. // // 应用信息
  217. // PackageInfo packageInfo = await PackageInfo.fromPlatform();
  218. // // 原生传的信息
  219. // Map setting = await NativeUtil.getSetting();
  220. //
  221. // if (Platform.isIOS) {
  222. // IosDeviceInfo iosInfo = await DeviceInfoPlugin().iosInfo;
  223. // // 设备
  224. // params["platform"] = "ios";
  225. // // 设备系统版本
  226. // params["system_version"] = iosInfo?.systemVersion;
  227. // // 设备型号 如:iPhone 11pro
  228. // params['device_model'] = iosInfo?.name;
  229. // // 设备型号,如:MLMF2LL/A
  230. // // params['device_number'] = iosInfo?.model;
  231. // // 设备ID
  232. // params['device_id'] = iosInfo?.identifierForVendor;
  233. // } else if (Platform.isAndroid) {
  234. // AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
  235. // // 设备
  236. // params["platform"] = "android";
  237. // // 设备系统版本
  238. // params["system_version"] = "Android ${androidInfo?.version?.release}";
  239. // // 设备型号 如:iPhone 11pro
  240. // params['device_model'] = androidInfo?.model;
  241. // // 设备型号,如:MLMF2LL/A
  242. // // params['device_number'] = androidInfo?.id;
  243. // // 设备Id
  244. // params['device_id'] = androidInfo?.androidId;
  245. // }
  246. // // 应用版本号
  247. // params["app_version_name"] = packageInfo.version;
  248. // params["app_version"] = -1 ;// packageInfo.buildNumber;
  249. // // 分辨率
  250. // params["solution"] =
  251. // "${window.physicalSize.width.floor()}*${window.physicalSize.height.floor()}";
  252. //
  253. // // 站长ID
  254. // String masterId = setting['master_id'];
  255. // if (null != masterId &&
  256. // masterId != '' &&
  257. // (!params.containsKey('master_id') || params['master_id'] == '')) {
  258. // params['master_id'] = masterId;
  259. // }
  260. //
  261. // // secret_key
  262. // params['secret_key'] = setting['secret_key'];
  263. //
  264. // // token 读取SP缓存中的用户token
  265. // String token = await SharedPreferencesUtil.getStringValue(
  266. // GlobalConfig.SHARED_KEY_TOKEN);
  267. // if (!EmptyUtil.isEmpty(token)) {
  268. // params['token'] = token;
  269. // }
  270. //
  271. // // 当前时间戳:秒
  272. // params["time"] = TimeUtil.getNowTime();
  273. //
  274. // // 过滤空字段,过滤首尾空格
  275. // Map<String, dynamic> filters = Map<String, dynamic>();
  276. // params.forEach((key, value) {
  277. // if (key != '' && value != '') {
  278. // filters[key] = (value is String) ? value.trim() : value;
  279. // }
  280. // });
  281. // params = filters;
  282. //
  283. // List<String> list = List<String>();
  284. // params.forEach((key, value) {
  285. // list.add(key.toString() + value.toString());
  286. // });
  287. // params["sign"] = signWithArray(list);
  288. // return params;
  289. // }
  290. /// 获取必须的请求参数(用于请求头部)
  291. static Future<Map<String, String>> _getMustHeadParams() async {
  292. Map<String, String> params = new HashMap<String, String>();
  293. // 应用信息
  294. PackageInfo packageInfo = await PackageInfo.fromPlatform();
  295. // 原生传的信息
  296. Map setting = await NativeUtil.getSetting();
  297. if (Platform.isIOS) {
  298. IosDeviceInfo iosInfo = await DeviceInfoPlugin().iosInfo;
  299. // 设备
  300. params["platform"] = "ios";
  301. // 设备系统版本
  302. params["os_version"] = iosInfo?.systemVersion?.toString();
  303. // 设备型号 如:iPhone 11pro
  304. params['device_model'] =
  305. EncodeUtil.encodeBase64(iosInfo?.name?.toString() ?? '');
  306. // 设备ID
  307. params['device_id'] = iosInfo?.identifierForVendor?.toString();
  308. // idfa
  309. params['idfa'] = iosInfo?.identifierForVendor?.toString();
  310. } else if (Platform.isAndroid) {
  311. AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
  312. // 设备
  313. params["platform"] = "android";
  314. // 设备系统版本
  315. params["os_version"] = "Android ${androidInfo?.version?.release}";
  316. // 设备型号 如:iPhone 11pro
  317. params['device_model'] = androidInfo?.model?.toString();
  318. // 设备Id
  319. params['device_id'] = androidInfo?.androidId?.toString();
  320. // imei
  321. params['imei'] = await _getImei();
  322. }
  323. // 应用版本号
  324. params["app_version_name"] = packageInfo.version?.toString();
  325. params["app_version"] = packageInfo.buildNumber?.toString();
  326. // 分辨率
  327. params["solution"] = "${window.physicalSize.width.floor()}*${window.physicalSize.height.floor()}";
  328. // 站长ID
  329. String masterId = setting['master_id'];
  330. if (null != masterId && masterId != '' && (!params.containsKey('master_id') || params['master_id'] == '')) {
  331. params['master_id'] = masterId; //!EmptyUtil.isEmpty(masterId) ? masterId : 'template_database';
  332. }
  333. // token 读取SP缓存中的用户token
  334. String token = await SharedPreferencesUtil.getStringValue(GlobalConfig.SHARED_KEY_TOKEN);
  335. if (EmptyUtil.isEmpty(token) && !bool.fromEnvironment("dart.vm.product")) {
  336. try {
  337. token = setting['token'];
  338. } catch (e, s) {
  339. print(s);
  340. print(e);
  341. }
  342. }
  343. if (!EmptyUtil.isEmpty(token)) {
  344. // params['token'] = token;
  345. params['Authorization'] = 'Bearer ' + token;
  346. }
  347. // secret_key
  348. params['secret_key'] = setting['secret_key'] ?? '';
  349. // 当前时间戳:秒
  350. params["time"] = TimeUtil.getNowTime();
  351. // 过滤空字段,过滤首尾空格
  352. Map<String, String> filters = Map<String, String>();
  353. params.forEach((key, value) {
  354. if (key != '' && value != '') {
  355. filters[key] = (value is String) ? value.trim() : value;
  356. }
  357. });
  358. params = filters;
  359. List<String> list = List<String>();
  360. params.forEach((key, value) {
  361. list.add(key.toString() + '=' + value.toString() + '&');
  362. });
  363. params["sign"] = signWithArray(list);
  364. params.remove('secret_key');
  365. return params;
  366. }
  367. /// 获取Android imei
  368. static Future<String> _getImei() async {
  369. try {
  370. return await ImeiPlugin.getImei(shouldShowRequestPermissionRationale: true);
  371. } catch (e, s) {
  372. Logger.error(e, s);
  373. }
  374. return null;
  375. }
  376. /// 获取请求缓存成功的数据
  377. static Future<void> _onCallBackCacheData(OnCache onCache, String cacheKey) async {
  378. // 读取缓存
  379. Map<String, dynamic> cacheMap = await SharedPreferencesUtil.getNetCacheResult(cacheKey);
  380. if (!EmptyUtil.isEmpty(cacheMap) &&
  381. cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
  382. (cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == GlobalConfig.RESPONSE_SUCCESS_CODE ||
  383. cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == '${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
  384. !EmptyUtil.isEmpty(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
  385. onCache(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
  386. return;
  387. }
  388. return;
  389. }
  390. /// 缓存请求成功的数据
  391. static void _setCallBackCacheData(String cacheKey, String value) async {
  392. SharedPreferencesUtil.setNetCacheResult(cacheKey, value);
  393. }
  394. /// 根据请求参数,获取缓存的数据
  395. static Future<dynamic> getRequestCachedData(String url, {Map<String, dynamic> params}) async {
  396. Map<String, dynamic> cacheMap = await SharedPreferencesUtil.getNetCacheResult(getRequestParamsCachedKey(params, url));
  397. if (!EmptyUtil.isEmpty(cacheMap) &&
  398. cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
  399. (cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == GlobalConfig.RESPONSE_SUCCESS_CODE ||
  400. cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == '${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
  401. !EmptyUtil.isEmpty(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
  402. return cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
  403. }
  404. return null;
  405. }
  406. /// 判断后台返回是否成功
  407. static bool isSuccess(Map<String, dynamic> data) {
  408. try {
  409. if (!EmptyUtil.isEmpty(data) &&
  410. (data[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == GlobalConfig.RESPONSE_SUCCESS_CODE ||
  411. data[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == '${GlobalConfig.RESPONSE_SUCCESS_CODE}')) {
  412. return true;
  413. }
  414. } catch (e) {
  415. return false;
  416. }
  417. return false;
  418. }
  419. /// 根据请求参数,获取缓存的Key
  420. static String getRequestParamsCachedKey(Map<String, dynamic> map, String path) {
  421. if (EmptyUtil.isEmpty(map)) {
  422. return EncodeUtil.generateMd5(path);
  423. }
  424. return EncodeUtil.generateMd5(path + map.toString());
  425. }
  426. // 七牛云文件上传
  427. static Future uploadFile(String url, File file, {String method = 'POST', Map<String, dynamic> params, OnSuccess onSuccess, OnError onError}) async {
  428. if (params == null) {
  429. params = {};
  430. }
  431. Dio dio = Dio(BaseOptions(
  432. method: "post",
  433. connectTimeout: 15000,
  434. receiveTimeout: 15000,
  435. contentType: Headers.jsonContentType,
  436. followRedirects: true,
  437. ));
  438. params['file'] = await MultipartFile.fromFile(file.path);
  439. FormData format = FormData.fromMap(params);
  440. return dio.request(url, data: format, options: Options(method: method));
  441. }
  442. /// 签名
  443. static String signWithArray(List<String> params) {
  444. // 字母升序
  445. params.sort();
  446. String result = "";
  447. params.forEach((param) {
  448. result += param;
  449. });
  450. result = result.substring(0, result.length - 1);
  451. return EncodeUtil.generateMd5(result);
  452. }
  453. /*
  454. * error统一处理
  455. */
  456. static void _formatError(DioError e) {
  457. if (e.type == DioErrorType.CONNECT_TIMEOUT) {
  458. Logger.error('连接超时: ${e.toString()}');
  459. } else if (e.type == DioErrorType.SEND_TIMEOUT) {
  460. Logger.error('请求超时: ${e.toString()}');
  461. } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
  462. Logger.error('响应超时: ${e.toString()}');
  463. } else if (e.type == DioErrorType.RESPONSE) {
  464. Logger.error('出现异常: ${e.toString()}');
  465. } else if (e.type == DioErrorType.CANCEL) {
  466. Logger.error('请求取消: ${e.toString()}');
  467. } else {
  468. Logger.error('未知错误: ${e.toString()}');
  469. }
  470. }
  471. }
  472. /**
  473. * @description: 网络请求拦截器
  474. * @param {type}
  475. * @return:
  476. */
  477. class _NetInterceptors extends InterceptorsWrapper {
  478. @override
  479. Future onRequest(RequestOptions options) {
  480. Logger.net(options?.uri?.toString(), data: options.data.toString());
  481. // TODO 加密?
  482. return super.onRequest(options);
  483. }
  484. @override
  485. Future onResponse(Response response) {
  486. Logger.endNet(response?.request?.uri?.toString(), data: response?.data?.toString() ?? '');
  487. // TODO 解密?
  488. return super.onResponse(response);
  489. }
  490. @override
  491. Future onError(DioError err) {
  492. // Logger.error(err);
  493. return super.onError(err);
  494. }
  495. }