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

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