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

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