基础库
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

net_util.dart 16 KiB

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