import 'dart:io'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:ftrecruiter/api/http_result.dart'; import 'package:get/get.dart'; import 'package:ftrecruiter/api/interceptors/auth_interceptor.dart'; import 'package:ftrecruiter/api/interceptors/log_res_interceptor.dart'; import 'package:ftrecruiter/api/interceptors/log_req_interceptor.dart'; import 'package:ftrecruiter/comm/constants/api_constants.dart'; import 'package:ftrecruiter/comm/constants/app_constant.dart'; import 'package:http/http.dart' as http; import '../comm/utils/log_utils.dart'; typedef NetSuccessCallback = Function(T data); typedef NetSuccessListCallback = Function(T data); typedef NetErrorCallback = Function(int? code, String? msg); enum HttpMethod { GET, POST } /// 网络请求相关封装 class ApiProvider extends GetConnect { // http.Request? _currentRequest; // http.StreamedResponse? _currentResponse; /// 默认简单的请求封装,回调的方式 Future requestNetEasy( String url, { HttpMethod? method, Map? headers, Map? query, Map? paths, NetSuccessCallback>? onSuccess, NetSuccessListCallback>? onSuccessList, NetErrorCallback? onError, }) async { //根据参数封装请求 var req = generateRequest(method, query, paths, url, headers); //开始请求 final startTime = DateTime.now().millisecond; var result = await req; final endTime = DateTime.now().millisecond; if (!AppConstant.inProduction) { final duration = endTime - startTime; Log.d('网络请求耗时 $duration 毫秒, 响应内容 ${result.body}}'); } if (result.statusCode == 200) { //网络请求正确之后获取正常的Json-Map Map jsonMap = result.body; //查看apiCode是否正确 int code = jsonMap['code']; if (code == 200) { if (jsonMap['data'] is List) { //返回数组 List list = jsonMap['data']; if (onSuccessList != null) { onSuccessList(list); } } else { //返回对象 if (onSuccess != null) { onSuccess(jsonMap['data']); } } } else { //Api错误 if (onError != null) { onError(jsonMap['code'], jsonMap['message']); } } } else { //网络请求错误 if (onError != null) { // result.bodyString 错误信息,这里没必要打印,拦截器中有打印的 onError(result.statusCode, result.statusText); } //吐司网络请求错误 SmartDialog.compatible.showToast("Request Network Error :${result.statusCode} ${result.statusText}"); } } /// 网络请求异步的Result封装 Future requestNetResult( String url, { HttpMethod? method, Map? headers, Map? query, Map? paths, }) async { //根据参数封装请求 var req = generateRequest(method, query, paths, url, headers); //开始请求 final startTime = DateTime.now().millisecond; var result = await req; final endTime = DateTime.now().millisecond; if (!AppConstant.inProduction) { final duration = endTime - startTime; Log.d('网络请求耗时 $duration 毫秒, 响应内容 ${result.body}}'); } if (result.statusCode == 200) { //网络请求正确之后获取正常的Json-Map Map jsonMap = result.body; //判断成功与失败 int code = jsonMap['code']; if (code == 200) { if (jsonMap['data'] is List) { //成功->返回数组 return HttpResult( isSuccess: true, listJson: jsonMap['data'], ); } else { //成功->返回对象 return HttpResult(isSuccess: true, dataJson: jsonMap['data']); } } else { //失败->返回Api错误 return HttpResult(isSuccess: false, errorCode: jsonMap['code'], errorMsg: jsonMap['message']); } } else { //失败->返回网络请求错误 return HttpResult(isSuccess: false, errorCode: result.statusCode, errorMsg: result.statusText); } } ///生成请求体 Future generateRequest(HttpMethod? method, Map? query, Map? paths, String url, Map? headers) async { Future req; if (method != null && method == HttpMethod.POST) { var map = {}; if (query != null || paths != null) { if (query != null) { map.addAll(query); } if (paths != null) { paths.forEach((key, value) { final file = File(value); map[key] = MultipartFile( file.readAsBytesSync(), filename: "file", ); }); } } var form = FormData(map); Log.d("Post请求FromData参数,fields:${form.fields.toString()} files:${form.files.toString()}"); //以Post-Body的方式上传 req = post(url, form, headers: headers); } else { //默认以Get-Params的方式上传 req = get(url, headers: headers, query: query); } return req; } @override void onInit() { httpClient.baseUrl = ApiConstants.baseUrl; httpClient.timeout = const Duration(seconds: 30); // httpClient.addResponseModifier(responseInterceptor); /// 统一添加身份验证请求头 httpClient.addRequestModifier(authInterceptor); /// 打印Log(生产模式去除) if (!AppConstant.inProduction) { httpClient.addRequestModifier(logReqInterceptor); } /// 打印Log(生产模式去除) // if (!AppConstant.inProduction) { // httpClient.addResponseModifier(logResInterceptor); // } } /// 取消网络请求并重新设置GetConnect ApiProvider cancelAndResetHttpClient() { httpClient.close(); Get.replace(ApiProvider()); return Get.find(); } }