YSNetWorking.dart 13 KB

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