基础库
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 

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