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

592 lines
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
  85. .POST, bool cache = false, bool showToast = true, int timeOut = 15000}) async {
  86. var paramsData = {'postData': params ?? {}, 'queryParameters': queryParameters ?? {}};
  87. // 根据请求参数,获取缓存的Key
  88. String cacheKey = getRequestParamsCachedKey(paramsData, path);
  89. // 参数签名 TODO 加密?
  90. // post请求的参数
  91. Map<String, dynamic> bodyParams = params;
  92. NetUtil.headParam = await _getMustHeadParams();
  93. Response response;
  94. try {
  95. Dio dio = await NetUtil
  96. .getInstance()
  97. .dio;
  98. response = await dio.request(
  99. path,
  100. data: !EmptyUtil.isEmpty(bodyParams) ? bodyParams : null,
  101. options: Options(method: enumToString(method), headers: headParam, receiveTimeout: timeOut),
  102. queryParameters: !EmptyUtil.isEmpty(queryParameters) ? queryParameters : null,
  103. );
  104. } on DioError catch (e) {
  105. _formatError(e);
  106. }
  107. try {
  108. var result = response.data is Map ? response.data : jsonDecode(response.data);
  109. // TODO 解密?
  110. if (isSuccess(result)) {
  111. // 缓存成功的数据
  112. if (cache) {
  113. _setCallBackCacheData(cacheKey, response.data is Map ? jsonEncode(response.data) : response.data);
  114. }
  115. return result;
  116. // 缓存返回的数据
  117. } else {
  118. Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]);
  119. ///
  120. /// 401000 验证用户失败(不提示Toast)
  121. /// 404004 没有找到对应模块(跳空页面,不提示toast)
  122. ///
  123. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] != 401000 && result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] != 404004) {
  124. if (showToast) {
  125. Fluttertoast.showToast(
  126. msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
  127. toastLength: Toast.LENGTH_SHORT,
  128. gravity: ToastGravity.BOTTOM,
  129. );
  130. }
  131. }
  132. ///
  133. /// 401003 用户被逼下线
  134. /// 退出登陆(清理token等用户信息)
  135. ///
  136. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '401003') {
  137. try {
  138. Future.delayed(Duration(seconds: 0)).then((onValue) {
  139. BuildContext context = navigatorKey.currentState.overlay.context;
  140. Provider.of<UserInfoNotifier>(context, listen: false).unLogin();
  141. });
  142. } catch (e, s) {
  143. Logger.error(e, s);
  144. }
  145. }
  146. ///非法用户
  147. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '401000') {
  148. try {
  149. Future.delayed(Duration(seconds: 0)).then((onValue) async {
  150. String token = await SharedPreferencesUtil.getStringValue(GlobalConfig.SHARED_KEY_TOKEN);
  151. if (token != null && token.length > 2) {
  152. BuildContext context = navigatorKey.currentState.overlay.context;
  153. Provider.of<UserInfoNotifier>(context, listen: false).unLogin();
  154. }
  155. });
  156. } catch (e, s) {
  157. Logger.error(e, s);
  158. }
  159. }
  160. ///
  161. /// 403028 账号被冻结
  162. /// 403029 账号被禁用
  163. /// 提示并且退出登录
  164. ///
  165. if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '403028' || result[GlobalConfig.HTTP_RESPONSE_KEY_CODE]?.toString() == '403029') {
  166. try {
  167. // 提示
  168. Fluttertoast.showToast(
  169. msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
  170. toastLength: Toast.LENGTH_SHORT,
  171. gravity: ToastGravity.BOTTOM,
  172. );
  173. // 退出登录
  174. Future.delayed(Duration(seconds: 0)).then((onValue) {
  175. BuildContext context = navigatorKey.currentState.overlay.context;
  176. Provider.of<UserInfoNotifier>(context, listen: false).unLogin();
  177. });
  178. } catch (e, s) {
  179. Logger.error(e, s);
  180. }
  181. }
  182. return result;
  183. }
  184. } catch (e) {
  185. return null;
  186. }
  187. }
  188. /// 异步请求
  189. static void request(String path,
  190. {NetMethod method = NetMethod.GET,
  191. Map<String, dynamic> params,
  192. Map<String, dynamic> queryParameters,
  193. OnSuccess onSuccess,
  194. OnError onError,
  195. OnCache onCache,
  196. bool showToast = true,int timeOut=15000}) async {
  197. var paramsData = {'postData': params ?? {}, 'queryParameters': queryParameters ?? {}};
  198. // 根据请求参数,获取缓存的Key
  199. String cacheKey = getRequestParamsCachedKey(paramsData, path);
  200. print("缓存Key" + cacheKey);
  201. // // 读取缓存回调
  202. if (onCache != null) {
  203. await _onCallBackCacheData(onCache, cacheKey);
  204. }
  205. try {
  206. Map result = await NetUtil.post(path, method: method,
  207. params: params,
  208. queryParameters: queryParameters,
  209. showToast: showToast,
  210. cache: onCache != null,timeOut: timeOut);
  211. // TODO 解密?
  212. if (isSuccess(result)) {
  213. if (onSuccess != null) {
  214. onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
  215. }
  216. return;
  217. }
  218. if (onError != null) {
  219. onError(!EmptyUtil.isEmpty(result)
  220. ? !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG])
  221. ? result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]
  222. : '未知错误'
  223. : '未知错误');
  224. }
  225. } catch (e) {
  226. Logger.error('error: ' + e.toString());
  227. if (onError != null) {
  228. onError(e?.toString() ?? '未知错误');
  229. }
  230. }
  231. return;
  232. }
  233. /// 统一添加必要的参数
  234. // static Future<Map<String, dynamic>> signParams(Map<String, dynamic> params) async {
  235. // // 应用信息
  236. // PackageInfo packageInfo = await PackageInfo.fromPlatform();
  237. // // 原生传的信息
  238. // Map setting = await NativeUtil.getSetting();
  239. //
  240. // if (Platform.isIOS) {
  241. // IosDeviceInfo iosInfo = await DeviceInfoPlugin().iosInfo;
  242. // // 设备
  243. // params["platform"] = "ios";
  244. // // 设备系统版本
  245. // params["system_version"] = iosInfo?.systemVersion;
  246. // // 设备型号 如:iPhone 11pro
  247. // params['device_model'] = iosInfo?.name;
  248. // // 设备型号,如:MLMF2LL/A
  249. // // params['device_number'] = iosInfo?.model;
  250. // // 设备ID
  251. // params['device_id'] = iosInfo?.identifierForVendor;
  252. // } else if (Platform.isAndroid) {
  253. // AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
  254. // // 设备
  255. // params["platform"] = "android";
  256. // // 设备系统版本
  257. // params["system_version"] = "Android ${androidInfo?.version?.release}";
  258. // // 设备型号 如:iPhone 11pro
  259. // params['device_model'] = androidInfo?.model;
  260. // // 设备型号,如:MLMF2LL/A
  261. // // params['device_number'] = androidInfo?.id;
  262. // // 设备Id
  263. // params['device_id'] = androidInfo?.androidId;
  264. // }
  265. // // 应用版本号
  266. // params["app_version_name"] = packageInfo.version;
  267. // params["app_version"] = -1 ;// packageInfo.buildNumber;
  268. // // 分辨率
  269. // params["solution"] =
  270. // "${window.physicalSize.width.floor()}*${window.physicalSize.height.floor()}";
  271. //
  272. // // 站长ID
  273. // String masterId = setting['master_id'];
  274. // if (null != masterId &&
  275. // masterId != '' &&
  276. // (!params.containsKey('master_id') || params['master_id'] == '')) {
  277. // params['master_id'] = masterId;
  278. // }
  279. //
  280. // // secret_key
  281. // params['secret_key'] = setting['secret_key'];
  282. //
  283. // // token 读取SP缓存中的用户token
  284. // String token = await SharedPreferencesUtil.getStringValue(
  285. // GlobalConfig.SHARED_KEY_TOKEN);
  286. // if (!EmptyUtil.isEmpty(token)) {
  287. // params['token'] = token;
  288. // }
  289. //
  290. // // 当前时间戳:秒
  291. // params["time"] = TimeUtil.getNowTime();
  292. //
  293. // // 过滤空字段,过滤首尾空格
  294. // Map<String, dynamic> filters = Map<String, dynamic>();
  295. // params.forEach((key, value) {
  296. // if (key != '' && value != '') {
  297. // filters[key] = (value is String) ? value.trim() : value;
  298. // }
  299. // });
  300. // params = filters;
  301. //
  302. // List<String> list = List<String>();
  303. // params.forEach((key, value) {
  304. // list.add(key.toString() + value.toString());
  305. // });
  306. // params["sign"] = signWithArray(list);
  307. // return params;
  308. // }
  309. static PackageInfo packageInfo;
  310. static Map setting;
  311. static IosDeviceInfo iosInfo;
  312. static AndroidDeviceInfo androidInfo;
  313. static String imei;
  314. /// 获取必须的请求参数(用于请求头部)
  315. static Future<Map<String, String>> _getMustHeadParams() async {
  316. Map<String, String> params = new HashMap<String, String>();
  317. // 应用信息
  318. if (packageInfo == null) {
  319. packageInfo = await PackageInfo.fromPlatform();
  320. }
  321. // 原生传的信息
  322. if (setting == null) {
  323. setting = await NativeUtil.getSetting();
  324. }
  325. if (Platform.isIOS) {
  326. if (iosInfo == null) {
  327. iosInfo = await DeviceInfoPlugin().iosInfo;
  328. }
  329. // 设备
  330. params["platform"] = "ios";
  331. // 设备系统版本
  332. params["os_version"] = iosInfo?.systemVersion?.toString();
  333. // 设备型号 如:iPhone 11pro
  334. params['device_model'] = EncodeUtil.encodeBase64(iosInfo?.name?.toString() ?? '');
  335. // 设备ID
  336. params['device_id'] = iosInfo?.identifierForVendor?.toString();
  337. // idfa
  338. params['idfa'] = iosInfo?.identifierForVendor?.toString();
  339. } else if (Platform.isAndroid) {
  340. if (androidInfo == null) {
  341. androidInfo = await DeviceInfoPlugin().androidInfo;
  342. }
  343. // 设备
  344. params["platform"] = "android";
  345. // 设备系统版本
  346. params["os_version"] = "Android ${androidInfo?.version?.release}";
  347. // 设备型号 如:iPhone 11pro
  348. params['device_model'] = androidInfo?.model?.toString();
  349. // 设备Id
  350. params['device_id'] = androidInfo?.androidId?.toString();
  351. }
  352. // 应用版本号
  353. params["app_version_name"] = packageInfo.version?.toString();
  354. params["AppVersionName"] = packageInfo.version?.toString();
  355. params["app_version"] = packageInfo.buildNumber?.toString();
  356. // 分辨率
  357. params["solution"] = "${window.physicalSize.width.floor()}*${window.physicalSize.height.floor()}";
  358. // 站长ID
  359. String masterId = setting['master_id'];
  360. if (null != masterId && masterId != '' && (!params.containsKey('master_id') || params['master_id'] == '')) {
  361. params['master_id'] = masterId; //!EmptyUtil.isEmpty(masterId) ? masterId : 'template_database';
  362. params['MasterId'] = masterId; //!EmptyUtil.isEmpty(masterId) ? masterId : 'template_database';
  363. }
  364. // token 读取SP缓存中的用户token
  365. String token = await SharedPreferencesUtil.getStringValue(GlobalConfig.SHARED_KEY_TOKEN);
  366. if (EmptyUtil.isEmpty(token) && !bool.fromEnvironment("dart.vm.product")) {
  367. try {
  368. token = setting['token'];
  369. } catch (e, s) {
  370. print(s);
  371. print(e);
  372. }
  373. }
  374. if (!EmptyUtil.isEmpty(token)) {
  375. // params['token'] = token;
  376. params['Authorization'] = 'Bearer ' + token;
  377. }
  378. // secret_key
  379. params['secret_key'] = setting['secret_key'] ?? '';
  380. // 当前时间戳:秒
  381. params["time"] = TimeUtil.getNowTime();
  382. imei = await getImei();
  383. print("获取到udid" + (imei ?? ""));
  384. params['imei'] = imei;
  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 FlutterAlibc.getUdid();
  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. }