YSNetWorking.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import 'dart:convert';
  2. import 'dart:isolate';
  3. import 'dart:typed_data';
  4. import 'package:dio/dio.dart';
  5. import 'package:encrypt/encrypt.dart';
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:flutter/foundation.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:ysairplane/code/YSBill.dart';
  10. import 'package:ysairplane/code/YSLogin.dart';
  11. import 'package:fluttertoast/fluttertoast.dart';
  12. import 'package:shared_preferences/shared_preferences.dart';
  13. import 'package:ysairplane/code/YSSetPayPass.dart';
  14. import 'YSTools.dart';
  15. //http://aviation.ytby0402.top
  16. //http://192.168.1.77:8082
  17. String base = 'http://aviation.ytby0402.top';
  18. int outTime = 20000;
  19. enum requestType{
  20. put,
  21. delete,
  22. get,
  23. post
  24. }
  25. typedef widgetCallback = Widget Function(dynamic value);
  26. ysRequestHttp(BuildContext context,{requestType type,String api,var parameter,bool isLoading,VoidCallback refresh,bool isToken}) async {
  27. FocusScope.of(context).unfocus();
  28. if(isLoading==true)showDialog(
  29. context: context,
  30. barrierDismissible: false,
  31. builder: (BuildContext context) {
  32. return LoadingDialog();
  33. }
  34. );
  35. try {
  36. SharedPreferences prefs = await SharedPreferences.getInstance();
  37. String token = prefs.getString('token');
  38. Map<String, dynamic> httpHeaders = {
  39. 'Accept': 'application/json,*/*',
  40. 'Content-Type': 'application/json',
  41. if(isToken==true)'Authentication': token??''
  42. };
  43. String url = base+api;
  44. print('请求网址:$url');
  45. if(isToken==true)print('token:$token');
  46. print('请求参数:$parameter');
  47. Response response;
  48. if(type==requestType.put){
  49. response = await Dio().put(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  50. }else if(type==requestType.post){
  51. response = await Dio().post(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  52. }else if(type==requestType.delete){
  53. response = await Dio().delete(url,data: parameter,options: Options(receiveTimeout: outTime,headers: httpHeaders));
  54. }else{
  55. response = await Dio().get(url,queryParameters: Map<String, dynamic>.from(parameter),options: Options(receiveTimeout: outTime,headers: httpHeaders));
  56. }
  57. if(isLoading==true)Navigator.of(context,rootNavigator: true).pop();
  58. LogUtil.d('请求结果:${response.data}');
  59. Map dict = response.data;
  60. if(dict['code']==200){
  61. ysFlutterToast(context,'操作成功');
  62. return dict;
  63. }else if(dict['code']==500){
  64. ysFlutterToast(context,'网络错误');
  65. }else if(dict['code']==404){
  66. ysFlutterToast(context,'接口请求错误');
  67. }else if(dict['code']==401){
  68. ysFlutterToast(context,'登陆已过期');
  69. Navigator.of(context,rootNavigator: true).push(
  70. CupertinoPageRoute(
  71. builder: (context){
  72. Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
  73. _prefer.then((value){
  74. value.remove('token');
  75. });
  76. return YSLogin();
  77. }
  78. )
  79. ).then((value){
  80. refresh();
  81. });
  82. }else if(dict['code']==400){
  83. ysFlutterToast(context,'没有检测到手机号');
  84. }else if(dict['code']==403){
  85. ysFlutterToast(context,'没有相关权限');
  86. }else if(dict['code']==405){
  87. ysFlutterToast(context,'没有注册,请注册');
  88. if(isToken==true)Navigator.of(context).push(
  89. CupertinoPageRoute(
  90. builder: (context){
  91. Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
  92. _prefer.then((value){
  93. value.remove('token');
  94. });
  95. return YSLogin();
  96. }
  97. )
  98. ).then((value){
  99. refresh();
  100. });
  101. }else if(dict['code']==406){
  102. ysFlutterToast(context,'密码错误');
  103. }else if(dict['code']==407){
  104. ysFlutterToast(context,'注册成功,需要新建账号');
  105. Navigator.of(context).push(
  106. CupertinoPageRoute(
  107. builder: (context){
  108. return YSBill();
  109. }
  110. )
  111. );
  112. }else if(dict['code']==408){
  113. ysFlutterToast(context,'用户名重复');
  114. }
  115. } catch (error) {
  116. if(isLoading==true)Navigator.of(context,rootNavigator: true).pop();
  117. print('网络错误:$error');
  118. ysFlutterToast(context,'网络错误');
  119. }
  120. }
  121. ysRequestHttpEncrypt(BuildContext context,{requestType type,String api,var parameter,bool isLoading,bool isToken}) async {
  122. FocusScope.of(context).unfocus();
  123. if(isLoading==true)showDialog(
  124. context: context,
  125. barrierDismissible: false,
  126. builder: (BuildContext context) {
  127. return LoadingDialog();
  128. }
  129. );
  130. try {
  131. SharedPreferences prefs = await SharedPreferences.getInstance();
  132. String token = prefs.getString('token');
  133. Map<String, dynamic> httpHeaders = {
  134. 'Accept': 'application/json,*/*',
  135. 'Content-Type': 'application/json',
  136. if(isToken==true)'Authentication': token??''
  137. };
  138. String url = base+api;
  139. print('请求网址:$url');
  140. if(isToken==true)print('token:$token');
  141. print('请求参数:$parameter');
  142. var requestStr = await rsaEncryption(json.encode(parameter));
  143. print('加密参数:${{'parmar':requestStr}}');
  144. Response response;
  145. if(type==requestType.put){
  146. response = await Dio().put(url,data: {'parmar':requestStr},options: Options(receiveTimeout: outTime,headers: httpHeaders));
  147. }else if(type==requestType.post){
  148. response = await Dio().post(url,data: {'parmar':requestStr},options: Options(receiveTimeout: outTime,headers: httpHeaders));
  149. }else if(type==requestType.delete){
  150. response = await Dio().delete(url,data: {'parmar':requestStr},options: Options(receiveTimeout: outTime,headers: httpHeaders));
  151. }else{
  152. response = await Dio().get(url,queryParameters: Map<String, dynamic>.from({'parmar':requestStr}),
  153. options: Options(receiveTimeout: outTime,headers: httpHeaders));
  154. }
  155. if(isLoading==true)Navigator.of(context,rootNavigator: true).pop();
  156. print('请求结果:${response.data}');
  157. Map dict = response.data;
  158. if(dict['code']==200){
  159. ysFlutterToast(context,'操作成功');
  160. if(response.data['data']!=null){
  161. String encrypt = response.data['data'];
  162. String dictStr = await rsaPrivateDecrypt(encrypt);
  163. LogUtil.d('解密后:$dictStr');
  164. return json.decode(dictStr);
  165. }else{
  166. return '';
  167. }
  168. }else if(dict['code']==500){
  169. ysFlutterToast(context,'网络错误');
  170. }else if(dict['code']==404){
  171. ysFlutterToast(context,'接口请求错误');
  172. }else if(dict['code']==401){
  173. ysFlutterToast(context,'登陆已过期');
  174. if(isToken==true)Navigator.of(context).push(
  175. CupertinoPageRoute(
  176. builder: (context){
  177. Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
  178. _prefer.then((value){
  179. value.remove('token');
  180. });
  181. return YSLogin();
  182. }
  183. )
  184. );
  185. }else if(dict['code']==400){
  186. ysFlutterToast(context,'没有检测到手机号');
  187. }else if(dict['code']==403){
  188. ysFlutterToast(context,'没有相关权限');
  189. }else if(dict['code']==405){
  190. ysFlutterToast(context,'没有注册,请注册');
  191. if(isToken==true)Navigator.of(context).push(
  192. CupertinoPageRoute(
  193. builder: (context){
  194. Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
  195. _prefer.then((value){
  196. value.remove('token');
  197. });
  198. return YSLogin();
  199. }
  200. )
  201. ).then((value){
  202. });
  203. }else if(dict['code']==406){
  204. ysFlutterToast(context,'密码错误');
  205. }else if(dict['code']==407){
  206. ysFlutterToast(context,'注册成功,需要新建账号');
  207. String encrypt = response.data['data'];
  208. var dictStr = await rsaPrivateDecrypt(encrypt);
  209. print('解密后:$dictStr');
  210. Navigator.of(context).push(
  211. CupertinoPageRoute(
  212. builder: (context){
  213. return YSBill();
  214. }
  215. )
  216. );
  217. }else if(dict['code']==408){
  218. ysFlutterToast(context,'用户名重复');
  219. }else if(dict['code']==804){
  220. return {'code':804};
  221. }else if(dict['code']==801){
  222. return {'code':801};
  223. }
  224. } catch (error) {
  225. if(isLoading==true)Navigator.of(context,rootNavigator: false).pop();
  226. print('网络错误:$error');
  227. ysFlutterToast(context,'网络错误');
  228. }
  229. }
  230. class LoadingDialog extends Dialog {
  231. @override
  232. Widget build(BuildContext context) {
  233. return Material(
  234. type: MaterialType.transparency,
  235. child: Center(
  236. child: SizedBox(
  237. width: 120.0,
  238. height: 120.0,
  239. child: Container(
  240. decoration: ShapeDecoration(
  241. color: Colors.black87,
  242. shape: RoundedRectangleBorder(
  243. borderRadius: BorderRadius.all(
  244. Radius.circular(8.0),
  245. ),
  246. ),
  247. ),
  248. child: Column(
  249. mainAxisAlignment: MainAxisAlignment.center,
  250. crossAxisAlignment: CrossAxisAlignment.center,
  251. children: <Widget>[
  252. CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.white),),
  253. Padding(
  254. padding: EdgeInsets.only(top: 20.0,),
  255. child: Text('正在请求',style: TextStyle(color: Colors.white),),
  256. ),
  257. ],
  258. ),
  259. ),
  260. ),
  261. ),
  262. );
  263. }
  264. }
  265. void ysFlutterToast(BuildContext context,String msg){
  266. FlutterToast(context).showToast(
  267. child: Container(
  268. padding: EdgeInsets.only(left: 20,right: 20,top: 5,bottom: 5),
  269. decoration: BoxDecoration(
  270. color: Colors.black87,
  271. borderRadius: BorderRadius.all(Radius.circular(25))
  272. ),
  273. child: Text(msg,style: TextStyle(fontSize: 14,color: Colors.white),),
  274. ),
  275. gravity: ToastGravity.BOTTOM,
  276. toastDuration: Duration(seconds: 2),
  277. );
  278. }
  279. //加密
  280. Future<String> rsaEncryption(String data) async {
  281. // 原始json转成字节数组
  282. List<int> sourceBytes = utf8.encode(data);
  283. final parser = RSAKeyParser();
  284. String key = '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCit9lK3Y4jrSBAWbbH4OYN4UzMLx7Q+zy0qKzyzMszeEitI8xLP9E4HanriT'
  285. 'X6iKFrdKJLb55DWga79trUozlzeI7XXu67S5VRr+YRLOXHbbTGrJVV63RnolgGd9jkzDd74wjVJIn8gylqlN+WG5/4daMHeEVQ8bGSq03aotzxrwIDAQAB';
  286. final publicKey = parser.parse(key);
  287. final encrypter = Encrypter(RSA(publicKey: publicKey));
  288. // 数据长度
  289. int inputLen = sourceBytes.length;
  290. // 加密最大长度
  291. int maxLen = 117;
  292. // 存放加密后的字节数组
  293. List<int> totalBytes = List();
  294. // 分段加密 步长为117
  295. for (var i = 0; i < inputLen; i += maxLen) {
  296. // 还剩多少字节长度
  297. int endLen = inputLen - i;
  298. List<int> item;
  299. if (endLen > maxLen) {
  300. item = sourceBytes.sublist(i, i + maxLen);
  301. }else{
  302. item = sourceBytes.sublist(i, i + endLen);
  303. }
  304. // 加密后的对象转换成字节数组再存放到容器
  305. totalBytes.addAll(encrypter.encryptBytes(item).bytes);
  306. }
  307. return base64.encode(totalBytes);
  308. }
  309. //解密
  310. Future<String> rsaPrivateDecrypt(String data) async {
  311. Uint8List sourceBytes = base64.decode(data);
  312. final parser = RSAKeyParser();
  313. String key = '-----BEGIN PRIVATE KEY-----\nMIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKK32UrdjiOtIEBZtsfg5g3hTMwvHtD7PLSorPLMyzN4SK0jzEs/0TgdqeuJNfqIoWt0oktvnkNaBrv22tSjOXN4jtde7rtLlVGv5hEs5c'
  314. 'dttMaslVXrdGeiWAZ32OTMN3vjCNUkifyDKWqU35Ybn/h1owd4RVDxsZKrTdqi3PGvAgMBAAECgYBQ/OanD40Ojr3NqZmC9JoscGXT/uP8qf91/7pNAsdkr8qkenvVPEc7AfCv7dQzBUwqepvIph6EcUuGxH/4c+FEn5X'
  315. 'QS/dNhdDHZtZ6E+DQzXHvrz7wVfDSecyYEKHRKw0WZmoCy6bfeDEf5zShmMJtmtakGq/+ES6U0DtLN4SWkQJBANCadJQm2ZSnHc0lCHkdkcSXsS+nhtRZ5EyKg3Xr81BClQXPtswYhPcNq9QSC/CBiaVNeC0TOOZEfaVEH'
  316. 'wc+bAkCQQDHsHPzMbnyZtPdv3MG1xukTgIuFsmg/LPM+hkuSNDUNR63PBNeVv59DwnFd+bgQTyZWQ97wm6Nx4ZQSfN3BE33AkB4RbWVfdjRZpE+KG38NtpGuRdF3JdWdAW3Q92L7eC5k8oMMbi5cCGpt84sVcNgha9xCXuSs'
  317. 'ZSK3056LQ6exJTRAkBSPmqDD0f2fkNkYSWO+6l20mozcU857tpe4eLdHUBlJjuwXB3eDRZji34KxodgdX3v6q5l2n6OBk9bYhnUOwGhAkB7+gFxeARigkNJl8CCVtpJ9oAped5NT8ebDS8KCAU2qu6Y9mz04bk2NbHAf6TmIm'
  318. 'oLCa/ORgP0Tn4HefEOfBKl';//根据存放位置更改
  319. final privateKey = parser.parse(key);
  320. final encrypter = Encrypter(RSA(privateKey: privateKey));
  321. // 数据长度
  322. int inputLen = sourceBytes.length;
  323. // 解密最大长度
  324. int maxLen = 128;
  325. // 存放加密后的字节数组
  326. List<int> totalBytes = List();
  327. // 分段解密 步长为128
  328. for (var i = 0; i < inputLen; i += maxLen) {
  329. // 还剩多少字节长度
  330. int endLen = inputLen - i;
  331. Uint8List item;
  332. if (endLen > maxLen) {
  333. item = sourceBytes.sublist(i, i + maxLen);
  334. }else{
  335. item = sourceBytes.sublist(i, i + endLen);
  336. }
  337. // 解密后的对象转换成字节数组再存放到容器
  338. totalBytes.addAll(encrypter.decryptBytes(Encrypted(item)));
  339. }
  340. return utf8.decode(totalBytes);
  341. }
  342. ysFutureWidge({widgetCallback data,VoidCallback net}){
  343. return FutureBuilder(
  344. future: net(),
  345. builder: (context, snapshot) {
  346. var widget;
  347. if (snapshot.connectionState == ConnectionState.done) {
  348. if (snapshot.hasError) {
  349. widget = Icon(
  350. Icons.error,
  351. color: Colors.red,
  352. size: 48,
  353. );
  354. }else if(snapshot.data==null||snapshot.data.isEmpty||snapshot.data==[]){
  355. widget = Container();
  356. } else {
  357. widget = data(snapshot);
  358. }
  359. } else {
  360. widget = Padding(
  361. padding: EdgeInsets.all(20),
  362. child: CircularProgressIndicator(),
  363. );
  364. }
  365. return Center(
  366. child: Container(
  367. child: widget,
  368. ),
  369. );
  370. },
  371. );
  372. }