123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276 |
- import 'dart:async';
- import 'dart:typed_data';
- import 'package:dio/dio.dart';
- import 'package:flutter/foundation.dart';
- import 'package:shared/utils/log_utils.dart';
- import '../core/platform_config.dart';
- import '../engine/network/network_engine.dart';
- import 'http_result.dart';
- enum CacheControl {
- noCache,
- onlyCache,
- cacheFirstOrNetworkPut,
- onlyNetworkPutCache,
- }
- enum HttpMethod { GET, POST }
- class DioEngine {
- late NetworkEngine networkEngine;
-
- DioEngine(String baseUrl, {List<Interceptor>? interceptors}) {
-
- networkEngine = NetworkEngine(baseUrl, interceptors);
- }
-
- void switchBaseUrl(String url){
- networkEngine.switchBaseUrlAndDio(url);
- }
-
- Future<HttpResult> requestNetResult(
- String url, {
- HttpMethod method = HttpMethod.GET,
- Map<String, String>? headers,
- Map<String, dynamic>? params,
- Map<String, String>? paths,
- Map<String, Uint8List>? pathStreams,
- CacheControl? cacheControl,
- Duration? cacheExpiration,
- ProgressCallback? send,
- ProgressCallback? receive,
- CancelToken? cancelToken,
- bool networkDebounce = false,
- bool isShowLoadingDialog = false,
- }) async {
-
- if (networkDebounce) {
- if (headers == null || headers.isEmpty) {
- headers = <String, String>{};
- }
- headers['network_debounce'] = "true";
- }
- if (isShowLoadingDialog) {
- if (headers == null || headers.isEmpty) {
- headers = <String, String>{};
- }
- headers['is_show_loading_dialog'] = "true";
- }
- return _executeRequests(
- url,
- method,
- headers,
- params,
- paths,
- pathStreams,
- cacheControl,
- cacheExpiration,
- send,
- receive,
- cancelToken,
- networkDebounce,
- );
- }
-
- Future<HttpResult> _executeRequests(
- String url,
- HttpMethod method,
- Map<String, String>? headers,
- Map<String, dynamic>? params,
- Map<String, String>? paths,
- Map<String, Uint8List>? pathStreams,
- CacheControl? cacheControl,
- Duration? cacheExpiration,
- ProgressCallback? send,
- ProgressCallback? receive,
- CancelToken? cancelToken,
- bool networkDebounce,
- ) async {
- try {
-
- Response response;
-
- Future<Response> executeGenerateRequest() async {
- return _generateRequest(
- method,
- params,
- paths,
- pathStreams,
- url,
- headers,
- cacheControl,
- cacheExpiration,
- send,
- receive,
- cancelToken,
- );
- }
- if (!kReleaseMode) {
- final startTime = DateTime.now();
- response = await executeGenerateRequest();
- final endTime = DateTime.now();
- final duration = endTime.difference(startTime).inMilliseconds;
- Log.d('网络请求耗时 $duration 毫秒,HttpCode:${response.statusCode} HttpMessage:${response.statusMessage} 响应内容 ${response.data}}');
- } else {
- response = await executeGenerateRequest();
- }
-
- if (response.statusCode == 200 || response.statusCode == 401 || response.statusCode == 422 || response.statusCode == 429) {
-
- Map<String, dynamic> jsonMap = response.data;
-
- if (jsonMap.containsKey('code')) {
- int code = jsonMap['code'];
-
- if (code == 200) {
- if (jsonMap['data'] is List<dynamic>) {
-
- return HttpResult(
- isSuccess: true,
- code: code,
- msg: jsonMap['message'],
- listJson: jsonMap['data'],
- );
- } else {
-
- return HttpResult(
- isSuccess: true,
- code: code,
- msg: jsonMap['message'],
- dataJson: jsonMap['data'],
- );
- }
-
- } else {
- if (jsonMap.containsKey('message')) {
-
- return HttpResult(isSuccess: false, code: code, errorMsg: jsonMap['message']);
- } else {
-
- return HttpResult(isSuccess: false, code: code, errorMsg: jsonMap['message']);
- }
- }
- } else {
-
- if (jsonMap.containsKey('message')) {
-
- return HttpResult(isSuccess: false, errorMsg: jsonMap['message']);
- } else {
-
- return HttpResult(isSuccess: false, errorMsg: jsonMap['message']);
- }
- }
- } else {
-
- return HttpResult(
- isSuccess: false,
- code: response.statusCode ?? PlatformConfig.networkDebounceCode,
- errorMsg: response.statusMessage,
- );
- }
- } on DioException catch (e) {
- Log.e("HttpProvider - DioException:$e 其他错误Error:${e.error.toString()}");
- if (e.response != null) {
-
- Log.d("网络请求错误,data:${e.response?.data}");
- return HttpResult(isSuccess: false, errorMsg: "错误码:${e.response?.statusCode} 错误信息:${e.response?.statusMessage}");
- } else if (e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.receiveTimeout) {
- return HttpResult(isSuccess: false, errorMsg: "网络连接超时,请稍后再试");
- } else if (e.type == DioExceptionType.cancel) {
- return HttpResult(isSuccess: false, errorMsg: "网络请求已取消");
- } else if (e.type == DioExceptionType.badCertificate) {
- return HttpResult(isSuccess: false, errorMsg: "网络连接证书无效");
- } else if (e.type == DioExceptionType.badResponse) {
- return HttpResult(isSuccess: false, errorMsg: "网络响应错误,请稍后再试");
- } else if (e.type == DioExceptionType.connectionError) {
- return HttpResult(isSuccess: false, errorMsg: "网络连接错误,请检查网络连接");
- } else if (e.type == DioExceptionType.unknown) {
-
- if (e.error != null) {
- if (e.error.toString().contains("HandshakeException")) {
- return HttpResult(isSuccess: false, errorMsg: "网络连接错误,请检查网络连接");
- } else {
- return HttpResult(isSuccess: false, errorMsg: e.error.toString());
- }
- } else {
- return HttpResult(isSuccess: false, errorMsg: "网络请求出现未知错误");
- }
- } else {
-
- return HttpResult(isSuccess: false, errorMsg: e.message);
- }
- }
- }
-
- Future<Response> _generateRequest(
- HttpMethod? method,
- Map<String, dynamic>? params,
- Map<String, String>? paths,
- Map<String, Uint8List>? pathStreams,
- String url,
- Map<String, String>? headers,
- CacheControl? cacheControl,
- Duration? cacheExpiration,
- ProgressCallback? send,
- ProgressCallback? receive,
- CancelToken? cancelToken,
- ) async {
- if (method != null && method == HttpMethod.POST) {
-
- return networkEngine.executePost(
- url: url,
- params: params,
- paths: paths,
- pathStreams: pathStreams,
- headers: headers,
- send: send,
- receive: receive,
- cancelToken: cancelToken,
- );
- } else {
-
- if (cacheControl != null) {
- if (headers == null || headers.isEmpty) {
- headers = <String, String>{};
- }
- headers['cache_control'] = cacheControl.name;
- if (cacheExpiration != null) {
- headers['cache_expiration'] = cacheExpiration.inMilliseconds.toString();
- }
- }
- return networkEngine.executeGet(
- url: url,
- params: params,
- headers: headers,
- cacheControl: cacheControl,
- cacheExpiration: cacheExpiration,
- receive: receive,
- cancelToken: cancelToken,
- );
- }
- }
- @override
- String toString() {
- return "networkEngine 的 baseUrl:${networkEngine.baseUrl}";
- }
- }
|