api_provider.dart 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import 'dart:io';
  2. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  3. import 'package:ftrecruiter/api/http_result.dart';
  4. import 'package:get/get.dart';
  5. import 'package:ftrecruiter/api/interceptors/auth_interceptor.dart';
  6. import 'package:ftrecruiter/api/interceptors/log_res_interceptor.dart';
  7. import 'package:ftrecruiter/api/interceptors/log_req_interceptor.dart';
  8. import 'package:ftrecruiter/comm/constants/api_constants.dart';
  9. import 'package:ftrecruiter/comm/constants/app_constant.dart';
  10. import 'package:http/http.dart' as http;
  11. import '../comm/utils/log_utils.dart';
  12. typedef NetSuccessCallback<T> = Function(T data);
  13. typedef NetSuccessListCallback<T> = Function(T data);
  14. typedef NetErrorCallback = Function(int? code, String? msg);
  15. enum HttpMethod { GET, POST }
  16. /// 网络请求相关封装
  17. class ApiProvider extends GetConnect {
  18. // http.Request? _currentRequest;
  19. // http.StreamedResponse? _currentResponse;
  20. /// 默认简单的请求封装,回调的方式
  21. Future<void> requestNetEasy(
  22. String url, {
  23. HttpMethod? method,
  24. Map<String, String>? headers,
  25. Map<String, dynamic>? query,
  26. Map<String, String>? paths,
  27. NetSuccessCallback<Map<String, dynamic>>? onSuccess,
  28. NetSuccessListCallback<List<dynamic>>? onSuccessList,
  29. NetErrorCallback? onError,
  30. }) async {
  31. //根据参数封装请求
  32. var req = generateRequest(method, query, paths, url, headers);
  33. //开始请求
  34. final startTime = DateTime.now().millisecond;
  35. var result = await req;
  36. final endTime = DateTime.now().millisecond;
  37. if (!AppConstant.inProduction) {
  38. final duration = endTime - startTime;
  39. Log.d('网络请求耗时 $duration 毫秒, 响应内容 ${result.body}}');
  40. }
  41. if (result.statusCode == 200) {
  42. //网络请求正确之后获取正常的Json-Map
  43. Map<String, dynamic> jsonMap = result.body;
  44. //查看apiCode是否正确
  45. int code = jsonMap['code'];
  46. if (code == 200) {
  47. if (jsonMap['data'] is List<dynamic>) {
  48. //返回数组
  49. List<dynamic> list = jsonMap['data'];
  50. if (onSuccessList != null) {
  51. onSuccessList(list);
  52. }
  53. } else {
  54. //返回对象
  55. if (onSuccess != null) {
  56. onSuccess(jsonMap['data']);
  57. }
  58. }
  59. } else {
  60. //Api错误
  61. if (onError != null) {
  62. onError(jsonMap['code'], jsonMap['message']);
  63. }
  64. }
  65. } else {
  66. //网络请求错误
  67. if (onError != null) {
  68. // result.bodyString 错误信息,这里没必要打印,拦截器中有打印的
  69. onError(result.statusCode, result.statusText);
  70. }
  71. //吐司网络请求错误
  72. SmartDialog.compatible.showToast("Request Network Error :${result.statusCode} ${result.statusText}");
  73. }
  74. }
  75. /// 网络请求异步的Result封装
  76. Future<HttpResult> requestNetResult(
  77. String url, {
  78. HttpMethod? method,
  79. Map<String, String>? headers,
  80. Map<String, dynamic>? query,
  81. Map<String, String>? paths,
  82. }) async {
  83. //根据参数封装请求
  84. var req = generateRequest(method, query, paths, url, headers);
  85. //开始请求
  86. final startTime = DateTime.now().millisecond;
  87. var result = await req;
  88. final endTime = DateTime.now().millisecond;
  89. if (!AppConstant.inProduction) {
  90. final duration = endTime - startTime;
  91. Log.d('网络请求耗时 $duration 毫秒, 响应内容 ${result.body}}');
  92. }
  93. if (result.statusCode == 200) {
  94. //网络请求正确之后获取正常的Json-Map
  95. Map<String, dynamic> jsonMap = result.body;
  96. //判断成功与失败
  97. int code = jsonMap['code'];
  98. if (code == 200) {
  99. if (jsonMap['data'] is List<dynamic>) {
  100. //成功->返回数组
  101. return HttpResult(
  102. isSuccess: true,
  103. listJson: jsonMap['data'],
  104. );
  105. } else {
  106. //成功->返回对象
  107. return HttpResult(isSuccess: true, dataJson: jsonMap['data']);
  108. }
  109. } else {
  110. //失败->返回Api错误
  111. return HttpResult(isSuccess: false, errorCode: jsonMap['code'], errorMsg: jsonMap['message']);
  112. }
  113. } else {
  114. //失败->返回网络请求错误
  115. return HttpResult(isSuccess: false, errorCode: result.statusCode, errorMsg: result.statusText);
  116. }
  117. }
  118. ///生成请求体
  119. Future<Response> generateRequest(HttpMethod? method, Map<String, dynamic>? query, Map<String, String>? paths,
  120. String url, Map<String, String>? headers) async {
  121. Future<Response> req;
  122. if (method != null && method == HttpMethod.POST) {
  123. var map = <String, dynamic>{};
  124. if (query != null || paths != null) {
  125. if (query != null) {
  126. map.addAll(query);
  127. }
  128. if (paths != null) {
  129. paths.forEach((key, value) {
  130. final file = File(value);
  131. map[key] = MultipartFile(
  132. file.readAsBytesSync(),
  133. filename: "file",
  134. );
  135. });
  136. }
  137. }
  138. var form = FormData(map);
  139. Log.d("Post请求FromData参数,fields:${form.fields.toString()} files:${form.files.toString()}");
  140. //以Post-Body的方式上传
  141. req = post(url, form, headers: headers);
  142. } else {
  143. //默认以Get-Params的方式上传
  144. req = get(url, headers: headers, query: query);
  145. }
  146. return req;
  147. }
  148. @override
  149. void onInit() {
  150. httpClient.baseUrl = ApiConstants.baseUrl;
  151. httpClient.timeout = const Duration(seconds: 30);
  152. // httpClient.addResponseModifier(responseInterceptor);
  153. /// 统一添加身份验证请求头
  154. httpClient.addRequestModifier(authInterceptor);
  155. /// 打印Log(生产模式去除)
  156. if (!AppConstant.inProduction) {
  157. httpClient.addRequestModifier(logReqInterceptor);
  158. }
  159. /// 打印Log(生产模式去除)
  160. // if (!AppConstant.inProduction) {
  161. // httpClient.addResponseModifier(logResInterceptor);
  162. // }
  163. }
  164. /// 取消网络请求并重新设置GetConnect
  165. ApiProvider cancelAndResetHttpClient() {
  166. httpClient.close();
  167. Get.replace(ApiProvider());
  168. return Get.find();
  169. }
  170. }