1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
|
import 'dart:convert';
import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart';
class XHttp { static const String GET = "GET"; static const String POST = "POST"; static const String PUT = "PUT"; static const String PATCH = "PATCH"; static const String DELETE = "DELETE";
static const CUSTOM_ERROR_CODE = 'DIO_CUSTOM_ERROR'; static const REQUEST_TYPE_STR = 'REQUEST'; static const RESPONSE_TYPE_STR = 'RESPONSE'; static const ERROR_TYPE_STR = 'RESPONSE_ERROR'; static const DEFAULT_LOAD_MSG = '请求中...';
static const CONNECT_TIMEOUT = 60000; static const RECEIVE_TIMEOUT = 60000; static const SEND_TIMEOUT = 60000;
static const DIALOG_TYPE_OTHERS = 'OTHERS'; static const DIALOG_TYPE_TOAST = 'TOAST'; static const DIALOG_TYPE_ALERT = 'ALERT'; static const DIALOG_TYPE_CUSTOM = 'CUSTOM';
static String loadMsg = DEFAULT_LOAD_MSG;
static String errorShowTitle = '发生错误啦';
static String errorShowMsg;
static CancelToken cancelToken = CancelToken();
static CancelToken whiteListCancelToken = CancelToken();
Map<String, CancelToken> _pendingRequests = {};
static Dio dio;
String _getBaseUrl() => 'https://xxx.com';
XHttp._internal() { if (null == dio) { dio = Dio(BaseOptions( baseUrl: _getBaseUrl(), headers: {'Content-Type': 'application/json'}, connectTimeout: CONNECT_TIMEOUT, receiveTimeout: RECEIVE_TIMEOUT, sendTimeout: SEND_TIMEOUT, extra: {'cancelDuplicatedRequest': true}, )); _init(); } }
static final XHttp _instance = XHttp._internal();
void _removePendingRequest(String tokenKey) { if (_pendingRequests.containsKey(tokenKey)) { _pendingRequests[tokenKey]?.cancel(tokenKey); _pendingRequests.remove(tokenKey); } }
void _init() { dio.interceptors.add( InterceptorsWrapper( onRequest: (RequestOptions options, handler) async { if (kDebugMode) { print("请求之前"); } if (dio.options.extra['cancelDuplicatedRequest'] == true && options.cancelToken == null) { String tokenKey = [ options.method, options.baseUrl + options.path, jsonEncode(options.data ?? {}), jsonEncode(options.queryParameters ?? {}) ].join('&'); _removePendingRequest(tokenKey); options.cancelToken = CancelToken(); options.extra['tokenKey'] = tokenKey; _pendingRequests[tokenKey] = options.cancelToken; } _handleRequest(options, handler); String token = 'Bearer xxxxx'; if (token != dio.options.headers['authorization']) { dio.options.headers['authorization'] = token; options.headers['authorization'] = token; } return handler.next(options); }, onResponse: (Response response, ResponseInterceptorHandler handler) { if (kDebugMode) { print("响应之前"); } _handleResponse(response, handler); RequestOptions option = response.requestOptions; if (dio.options.extra['cancelDuplicatedRequest'] == true && option.cancelToken == null) { _removePendingRequest(option.extra['tokenKey']); } String code = (response?.data ?? {})['code']; String msg = (response?.data ?? {})['msg'] ?? response.statusMessage; bool isSuccess = option.contentType != null && option.contentType.contains("text") || code == '0'; response.data = Result(response.data, isSuccess, response.statusCode, msg, headers: response.headers); return handler.next(response); }, onError: (DioError error, handler) { if (kDebugMode) { print("出错之前"); } _handleError(error); if (!CancelToken.isCancel(error) && dio.options.extra['cancelDuplicatedRequest'] == true) { _pendingRequests.clear(); } if (error.response != null && error.response?.data != null) { error.response.data = Result( error.response.data, false, error.response?.statusCode, errorShowMsg ?? error.response?.statusMessage, headers: error.response?.headers); } else { throw Exception(errorShowMsg); } return handler.next(error); }, ), ); }
void _handleRequest(RequestOptions options, handler) { Toast.hide(); Toast.loading(loadMsg); Map logData = { 'url': options.baseUrl + options.path, 'method': options.method, 'headers': options.headers, 'data': options.data ?? options.queryParameters, }; _dealRequestInfo(logData, REQUEST_TYPE_STR); }
void _handleResponse(Response response, handler) { Map logData = { 'url': response.requestOptions.uri, 'method': response.requestOptions.method, 'headers': response.headers, 'data': response.data, 'statusCode': response.statusCode, 'statusMessage': response.statusMessage, }; _dealRequestInfo(logData, RESPONSE_TYPE_STR); Toast.hide(); }
void _handleError(DioError error) { String errorTypeInfo = '其他错误!'; switch (error.type) { case DioErrorType.connectTimeout: errorTypeInfo = '连接超时!'; break; case DioErrorType.sendTimeout: errorTypeInfo = "请求超时!"; break; case DioErrorType.receiveTimeout: errorTypeInfo = "响应超时!"; break; case DioErrorType.response: errorTypeInfo = "服务异常!"; break; case DioErrorType.cancel: errorTypeInfo = "请求取消!"; break; case DioErrorType.other: default: break; } Map logData = { 'url': error.requestOptions.baseUrl + error.requestOptions.path, 'method': error.requestOptions.method, 'headers': error.response?.headers, 'data': error.response?.data, 'statusCode': error.response?.statusCode, 'statusMessage': error.response?.statusMessage, 'errorType': error.type, 'errorMessage': error.message, 'errorTypeInfo': errorTypeInfo, }; _dealRequestInfo(logData, ERROR_TYPE_STR); Toast.hide(); errorShowMsg = "$errorShowTitle ${error.response?.statusCode ?? 'unknown'} $errorTypeInfo \n ${error.response?.statusMessage ?? ''} ${error.message ?? ''} \n ${error.response?.data ?? ''}"; }
String _dealRequestInfo(Map logData, String logType) { String logStr = "\n"; logStr += "========================= $logType START =========================\n"; logStr += "- URL: ${logData['url']} \n"; logStr += "- METHOD: ${logData['method']} \n"; if (logData['data'] != null) { logStr += "- ${logType}_BODY: \n"; logStr += "!!!!!----------*!*##~##~##~##*!*##~##~##~##*!*----------!!!!! \n"; logStr += "${parseData(logData['data'])} \n"; logStr += "!!!!!----------*!*##~##~##~##*!*##~##~##~##*!*----------!!!!! \n"; } if (logType.contains(RESPONSE_TYPE_STR)) { logStr += "- STATUS_CODE: ${logData['statusCode']} \n"; logStr += "- STATUS_MSG: ${logData['statusMessage']} \n"; } if (logType == ERROR_TYPE_STR) { logStr += "- ERROR_TYPE: ${logData['errorType']} \n"; logStr += "- ERROR_MSG: ${logData['errorMessage']} \n"; logStr += "- ERROR_TYPE_INFO: ${logData['errorTypeInfo']} \n"; } logStr += "========================= $logType E N D =========================\n"; logWrapped(logStr); return logStr; }
Future _showResultDialog(Response response, resultDialogConfig) async { if (response == null) { return; } resultDialogConfig = resultDialogConfig ?? {}; String dialogType = resultDialogConfig['type'] ?? XHttp.DIALOG_TYPE_TOAST; if (dialogType == XHttp.DIALOG_TYPE_OTHERS) { return; } bool isSuccess = response?.data?.success ?? false; String msg = response?.data?.msg ?? '未知错误'; if (dialogType == XHttp.DIALOG_TYPE_TOAST) { isSuccess ? Toast.show(resultDialogConfig['successMsg'] ?? msg, type: Toast.SUCCESS) : Toast.show(resultDialogConfig['errorMsg'] ?? msg, type: Toast.ERROR); return; } if (dialogType == XHttp.DIALOG_TYPE_ALERT) { return; } if (dialogType == XHttp.DIALOG_TYPE_CUSTOM) { if (isSuccess) { if (resultDialogConfig['onSuccess'] != null) { resultDialogConfig['onSuccess'](response.data); } } else { if (resultDialogConfig['onError'] != null) { resultDialogConfig['onError'](response.data); } } } }
void _catchOthersError(e) { String errMsg = "${errorShowMsg ?? e}$CUSTOM_ERROR_CODE".split(CUSTOM_ERROR_CODE)[0]; int errMsgLength = errMsg.length; String errshowMsg = errMsgLength > 300 ? errMsg.substring(0, 150) : errMsg; if (e is DioError) { if (CancelToken.isCancel(e)) { Toast.show('Cancel Request Successful'); return; } Toast.show(errshowMsg, type: Toast.WARNING); return; } Toast.show(errshowMsg + "\n......", type: Toast.ERROR); }
static XHttp getInstance({String baseUrl, String msg}) { String targetBaseUrl = baseUrl ?? _instance._getBaseUrl(); loadMsg = msg ?? DEFAULT_LOAD_MSG; if (dio.options.baseUrl != targetBaseUrl) { dio.options.baseUrl = targetBaseUrl; } return _instance; }
static XHttp cancelRequest() { Toast.hide(); if (dio.options.extra['cancelDuplicatedRequest'] == true) { _instance._pendingRequests.forEach((tokenKey, cancelToken) { cancelToken.cancel('cancel request $tokenKey'); }); } else { cancelToken.cancel('cancel request'); cancelToken = CancelToken(); } return _instance; }
static XHttp cancelWhiteListRequest() { Toast.hide(); whiteListCancelToken.cancel('cancel whiteList request'); whiteListCancelToken = CancelToken(); return _instance; }
static CancelToken getCancelToken() { return cancelToken; }
static CancelToken getWhiteListCancelToken() { return whiteListCancelToken; }
static CancelToken getNewCancelToken() { return CancelToken(); }
Future get(String url, [Map<String, dynamic> params, resultDialogConfig, bool isCancelWhiteList = false]) async { Response response; var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } } try { if (params != null) { response = await dio.get(url, queryParameters: params, cancelToken: requestToken); return response.data; } else { response = await dio.get(url, cancelToken: requestToken); return response.data; } } catch (e) { _catchOthersError(e); } finally { _showResultDialog(response, resultDialogConfig); } }
Future post(String url, [Map<String, dynamic> data, resultDialogConfig, bool isCancelWhiteList = false]) async { Response response; var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } } try { response = await dio.post(url, data: data, cancelToken: requestToken); return response.data; } catch (e) { _catchOthersError(e); } finally { _showResultDialog(response, resultDialogConfig); } }
Future put(String url, [Map<String, dynamic> data, resultDialogConfig, bool isCancelWhiteList = false]) async { Response response; var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } } try { response = await dio.put(url, data: data, cancelToken: requestToken); return response.data; } catch (e) { _catchOthersError(e); } finally { _showResultDialog(response, resultDialogConfig); } }
Future patch(String url, [Map<String, dynamic> data, resultDialogConfig, bool isCancelWhiteList = false]) async { Response response; var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } } try { response = await dio.patch(url, data: data, cancelToken: requestToken); return response.data; } catch (e) { _catchOthersError(e); } finally { _showResultDialog(response, resultDialogConfig); } }
Future delete(String url, [Map<String, dynamic> data, resultDialogConfig, bool isCancelWhiteList = false]) async { Response response; var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } } try { response = await dio.delete(url, data: data, cancelToken: requestToken); return response.data; } catch (e) { _catchOthersError(e); } finally { _showResultDialog(response, resultDialogConfig); } }
static Future request( String url, { String method = XHttp.GET, Map<String, dynamic> queryParameters, Map<String, dynamic> data, bool isCancelWhiteList = false, resultDialogConfig, Options options, void Function(int, int) onSendProgress, void Function(int, int) onReceiveProgress, String msg, String baseUrl, }) async { XHttp.getInstance(baseUrl: baseUrl, msg: msg); Response response;
var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } }
try { response = await dio.request( url, options: options ?? Options(method: method, contentType: Headers.formUrlEncodedContentType), queryParameters: queryParameters, data: data, cancelToken: requestToken, onReceiveProgress: onReceiveProgress, onSendProgress: onSendProgress, ); return response.data; } catch (e) { _instance._catchOthersError(e); } finally { _instance._showResultDialog( response, resultDialogConfig ?? {'type': XHttp.DIALOG_TYPE_OTHERS}, ); } }
Future downloadFile(urlPath, savePath, [resultDialogConfig, bool isCancelWhiteList = false]) async { Response response; var requestToken; if (dio.options.extra['cancelDuplicatedRequest'] != true || isCancelWhiteList) { if (isCancelWhiteList) { requestToken = whiteListCancelToken; } else { requestToken = cancelToken; } } try { response = await dio.download(urlPath, savePath, onReceiveProgress: (int count, int total) { print("$count $total"); }, cancelToken: requestToken); return response.data; } catch (e) { _catchOthersError(e); } finally { _showResultDialog(response, resultDialogConfig); } }
static String getBaseUrl() { return dio.options.baseUrl; }
static XHttp setBaseUrl(String baseUrl) { dio.options.baseUrl = baseUrl; return _instance; }
static Map getHeaders() { return dio.options.headers; }
static dynamic getHeader(String key) { return dio.options.headers[key]; }
static XHttp setHeaders(Map headers) { dio.options.headers = headers; return _instance; }
static XHttp setHeader(String key, String value) { dio.options.headers[key] = value; return _instance; }
static XHttp removeHeader(String key) { dio.options.headers.remove(key); return _instance; }
static XHttp removeAllHeaders() { dio.options.headers.clear(); return _instance; }
static Map getRequestTimeout() { return { 'connectTimeout': dio.options.connectTimeout, 'receiveTimeout': dio.options.receiveTimeout, 'sendTimeout': dio.options.sendTimeout }; }
static XHttp setRequestTimeout(int timeout) { dio.options.connectTimeout = timeout; dio.options.receiveTimeout = timeout; dio.options.sendTimeout = timeout; return _instance; }
static XHttp setConnectTimeout(int timeout) { dio.options.connectTimeout = timeout; return _instance; }
static XHttp setReceiveTimeout(int timeout) { dio.options.receiveTimeout = timeout; return _instance; }
static XHttp setSendTimeout(int timeout) { dio.options.sendTimeout = timeout; return _instance; }
static Map<String, dynamic> getAuthUser() { String token = dio.options.headers['authorization']; if (null == token) { return null; } return {'account': 'xxx', 'name': 'xxx', 'roles': 'xxx'}; }
static XHttp setAuthToken([String token]) { if (null == token) { dio.options.headers.remove('authorization'); } else { dio.options.headers['authorization'] = token; } return _instance; }
static XHttp setErrorTitle(String msg) { errorShowTitle = msg; return _instance; }
static bool isCancel(e) { return CancelToken.isCancel(e); }
}
String parseData(data) { String responseStr = ""; if (data is Map) { responseStr += data.mapToStructureString(); } else if (data is FormData) { final formDataMap = Map() ..addEntries(data.fields) ..addEntries(data.files); responseStr += formDataMap.mapToStructureString(); } else if (data is List) { responseStr += data.listToStructureString(); } else { responseStr += data.toString(); } return responseStr; }
void logWrapped(String text) { final pattern = RegExp('.{1,800}'); pattern.allMatches(text).forEach((match) => print(match.group(0))); }
extension Map2StringEx on Map { String mapToStructureString({int indentation = 0, String space = " "}) { if (this == null || this.isEmpty) { return "$this"; } String result = ""; String indentationContent = space * indentation; result += "{"; this.forEach((key, value) { if (value is Map) { result += "\n$indentationContent" + "\"$key\": ${value.mapToStructureString(indentation: indentation + 1)},"; } else if (value is List) { result += "\n$indentationContent" + "\"$key\": ${value.listToStructureString(indentation: indentation + 1)},"; } else { result += "\n$indentationContent" + "\"$key\": ${value is String ? "\"$value\"," : "$value,"}"; } }); result = result.substring(0, result.length - 1); result += "\n$indentationContent}"; return result; } }
extension List2StringEx on List { String listToStructureString({int indentation = 0, String space = " "}) { if (this == null || this.isEmpty) { return "$this"; } String result = ""; String indentationContent = space * indentation; result += "["; for (var value in this) { if (value is Map) { result += "\n$indentationContent" + space + "${value.mapToStructureString(indentation: indentation + 1)},"; } else if (value is List) { result += value.listToStructureString(indentation: indentation + 1); } else { result += "\n$indentationContent" + value is String ? "\"$value\"," : "$value,"; } } result = result.substring(0, result.length - 1); result += "\n$indentationContent]"; return result; } }
class Result { var data; bool success; int code; String msg; var headers; Result(this.data, this.success, this.code, this.msg, {this.headers}); }
class Toast { Toast._() { } static final Toast _instance = Toast._();
static const String SUCCESS = "SUCCESS"; static const String ERROR = "ERROR"; static const String WARNING = "WARNING"; static const String INFO = "INFO";
static loading(String msg) { EasyLoading.show(status: msg); }
static progeress(double value, String msg) { EasyLoading.showProgress(value, status: msg); }
static show(String msg, {String type}) { switch (type) { case Toast.SUCCESS: EasyLoading.showSuccess(msg); break; case Toast.ERROR: EasyLoading.showError(msg); break; case Toast.WARNING: EasyLoading.showInfo(msg); break; case Toast.INFO: default: EasyLoading.showToast(msg); break; } }
static hide() { EasyLoading.dismiss(); } }
|