基础库
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

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