123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198 |
- 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<T> = Function(T data);
- typedef NetSuccessListCallback<T> = 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<void> requestNetEasy(
- String url, {
- HttpMethod? method,
- Map<String, String>? headers,
- Map<String, dynamic>? query,
- Map<String, String>? paths,
- NetSuccessCallback<Map<String, dynamic>>? onSuccess,
- NetSuccessListCallback<List<dynamic>>? 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<String, dynamic> jsonMap = result.body;
- //查看apiCode是否正确
- int code = jsonMap['code'];
- if (code == 200) {
- if (jsonMap['data'] is List<dynamic>) {
- //返回数组
- List<dynamic> 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<HttpResult> requestNetResult(
- String url, {
- HttpMethod? method,
- Map<String, String>? headers,
- Map<String, dynamic>? query,
- Map<String, String>? 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<String, dynamic> jsonMap = result.body;
- //判断成功与失败
- int code = jsonMap['code'];
- if (code == 200) {
- if (jsonMap['data'] is List<dynamic>) {
- //成功->返回数组
- 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<Response> generateRequest(HttpMethod? method, Map<String, dynamic>? query, Map<String, String>? paths,
- String url, Map<String, String>? headers) async {
- Future<Response> req;
- if (method != null && method == HttpMethod.POST) {
- var map = <String, dynamic>{};
- 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();
- }
- }
|