dio

所属分类:人工智能/神经网络/深度学习
开发工具:Dart
文件大小:2931KB
下载次数:0
上传日期:2023-04-28 10:16:46
上 传 者sh-1993
说明:  no intro
(A powerful HTTP client for Dart and Flutter, which supports global settings, Interceptors, FormData, aborting and canceling a request, files uploading and downloading, requests timeout, custom adapters, etc.)

文件列表:
.idea (0, 2023-05-26)
.idea\dio.iml (2107, 2023-05-26)
.idea\modules.xml (838, 2023-05-26)
CODEOWNERS (13, 2023-05-26)
LICENSE (1104, 2023-05-26)
analysis_options.yaml (262, 2023-05-26)
dio (0, 2023-05-26)
dio\CHANGELOG.md (8071, 2023-05-26)
dio\LICENSE (1104, 2023-05-26)
dio\analysis_options.yaml (34, 2023-05-26)
dio\dart_test.yaml (56, 2023-05-26)
dio\example (0, 2023-05-26)
dio\example\dio.dart (220, 2023-05-26)
dio\lib (0, 2023-05-26)
dio\lib\browser.dart (132, 2023-05-26)
dio\lib\dio.dart (740, 2023-05-26)
dio\lib\io.dart (150, 2023-05-26)
dio\lib\src (0, 2023-05-26)
dio\lib\src\adapter.dart (2963, 2023-05-26)
dio\lib\src\adapters (0, 2023-05-26)
dio\lib\src\adapters\browser_adapter.dart (6994, 2023-05-26)
... ...

# dio [![Pub](https://img.shields.io/pub/v/dio.svg)](https://pub.dev/packages/dio) [![Dev](https://img.shields.io/pub/v/dio.svg?label=dev&include_prereleases)](https://pub.dev/packages/dio) Language: English | [“–](README-ZH.md) A powerful HTTP client for Dart/Flutter, which supports global configuration, interceptors, FormData, request cancellation, file uploading/downloading, timeout, and custom adapters etc.
Table of content * [dio](#dio) * [Get started](#get-started) * [Add dependency](#add-dependency) * [Super simple to use](#super-simple-to-use) * [Awesome dio](#awesome-dio) * [Plugins](#plugins) * [Related Projects](#related-projects) * [Examples](#examples) * [Dio APIs](#dio-apis) * [Creating an instance and set default configs.](#creating-an-instance-and-set-default-configs) * [Request Options](#request-options) * [Response](#response) * [Interceptors](#interceptors) * [Resolve and reject the request](#resolve-and-reject-the-request) * [QueuedInterceptor](#queuedinterceptor) * [Example](#example) * [LogInterceptor](#loginterceptor) * [Custom Interceptor](#custom-interceptor) * [Handling Errors](#handling-errors) * [DioException](#dioexception) * [DioExceptionType](#dioexceptiontype) * [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) * [Sending FormData](#sending-formdata) * [Multiple files upload](#multiple-files-upload) * [Reuse `FormData`s and `MultipartFile`s](#reuse-formdata-s-and-multipartfile-s) * [Transformer](#transformer) * [In Flutter](#in-flutter) * [Other example](#other-example) * [HttpClientAdapter](#httpclientadapter) * [Using proxy](#using-proxy) * [HTTPS certificate verification](#https-certificate-verification) * [HTTP/2 support](#http2-support) * [Cancellation](#cancellation) * [Extends Dio class](#extends-dio-class) * [Cross-Origin Resource Sharing on Web (CORS)](#cross-origin-resource-sharing-on-web--cors-)
## Get started > Checkout the [Migration Guide](migration_guide.md) for breaking changes between versions. ### Add dependency You can use the command to add dio as a dependency with the latest stable version: ```console $ dart pub add dio ``` Or you can manually add dio into the dependencies section in your pubspec.yaml: ```yaml dependencies: dio: ^replace-with-latest-version ``` The latest version is: ![Pub](https://img.shields.io/pub/v/dio.svg) The latest version including pre-releases is: ![Pub](https://img.shields.io/pub/v/dio?include_prereleases) ### Super simple to use ```dart import 'package:dio/dio.dart'; final dio = Dio(); void getHttp() async { final response = await dio.get('https://dart.dev'); print(response); } ``` ## Awesome dio ‰ A curated list of awesome things related to dio. ### Plugins | Repository | Status | Description | |--------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------| | [dio_cookie_manager](https://github.com/cfug/dio/blob/main/plugins/cookie_manager) | [![Pub](https://img.shields.io/pub/v/dio_cookie_manager.svg)](https://pub.dev/packages/dio_cookie_manager) | A cookie manager for Dio | | [dio_http2_adapter](https://github.com/cfug/dio/blob/main/plugins/http2_adapter) | [![Pub](https://img.shields.io/pub/v/dio_http2_adapter.svg)](https://pub.dev/packages/dio_http2_adapter) | A Dio HttpClientAdapter which support Http/2.0 | | [native_dio_adapter](https://github.com/cfug/dio/blob/main/plugins/native_dio_adapter) | [![Pub](https://img.shields.io/pub/v/native_dio_adapter.svg)](https://pub.dev/packages/native_dio_adapter) | An adapter for Dio which makes use of cupertino_http and cronet_http to delegate HTTP requests to the native platform. | | [dio_smart_retry](https://github.com/rodion-m/dio_smart_retry) | [![Pub](https://img.shields.io/pub/v/dio_smart_retry.svg)](https://pub.dev/packages/dio_smart_retry) | Flexible retry library for Dio | | [http_certificate_pinning](https://github.com/diefferson/http_certificate_pinning) | [![Pub](https://img.shields.io/pub/v/http_certificate_pinning.svg)](https://pub.dev/packages/http_certificate_pinning) | Https Certificate pinning for Flutter | | [dio_intercept_to_curl](https://github.com/blackflamedigital/dio_intercept_to_curl) | [![Pub](https://img.shields.io/pub/v/dio_intercept_to_curl.svg)](https://pub.dev/packages/dio_intercept_to_curl) | A Flutter curl-command generator for Dio. | | [dio_cache_interceptor](https://github.com/llfbandit/dio_cache_interceptor) | [![Pub](https://img.shields.io/pub/v/dio_cache_interceptor.svg)](https://pub.dev/packages/dio_cache_interceptor) | Dio HTTP cache interceptor with multiple stores respecting HTTP directives (or not) | | [dio_http_cache](https://github.com/hurshi/dio-http-cache) | [![Pub](https://img.shields.io/pub/v/dio_http_cache.svg)](https://pub.dev/packages/dio_http_cache) | A simple cache library for Dio like Rxcache in Android | | [pretty_dio_logger](https://github.com/Milad-Akarie/pretty_dio_logger) | [![Pub](https://img.shields.io/pub/v/pretty_dio_logger.svg)](https://pub.dev/packages/pretty_dio_logger) | Pretty Dio logger is a Dio interceptor that logs network calls in a pretty, easy to read format. | | [dio_image_provider](https://github.com/ueman/image_provider) | [![Pub](https://img.shields.io/pub/v/dio_image_provider.svg)](https://pub.dev/packages/dio_image_provider) | An image provider which makes use of package:dio to instead of dart:io | | [flutter_ume_kit_dio](https://github.com/cfug/flutter_ume_kits/tree/main/packages/flutter_ume_kit_dio) | [![Pub](https://img.shields.io/pub/v/flutter_ume_kit_dio.svg)](https://pub.dev/packages/flutter_ume_kit_dio) | A debug kit of dio on flutter_ume | ### Related Projects Welcome to submit third-party plugins and related libraries in [here](https://github.com/cfug/dio/issues/347). ## Examples Performing a `GET` request: ```dart import 'package:dio/dio.dart'; final dio = Dio(); void request() async { Response response; response = await dio.get('/test?id=12&name=dio'); print(response.data.toString()); // The below request is the same as above. response = await dio.get( '/test', queryParameters: {'id': 12, 'name': 'dio'}, ); print(response.data.toString()); } ``` Performing a `POST` request: ```dart response = await dio.post('/test', data: {'id': 12, 'name': 'dio'}); ``` Performing multiple concurrent requests: ```dart response = await Future.wait([dio.post('/info'), dio.get('/token')]); ``` Downloading a file: ```dart response = await dio.download( 'https://pub.dev/', (await getTemporaryDirectory()).path + 'pub.html', ); ``` Get response stream: ```dart final rs = await dio.get( url, options: Options(responseType: ResponseType.stream), // Set the response type to `stream`. ); print(rs.data.stream); // Response stream. ``` Get response with bytes: ```dart final rs = await Dio().get>( url, options: Options(responseType: ResponseType.bytes), // Set the response type to `bytes`. ); print(rs.data); // Type: List. ``` Sending a `FormData`: ```dart final formData = FormData.fromMap({ 'name': 'dio', 'date': DateTime.now().toIso8601String(), }); final response = await dio.post('/info', data: formData); ``` Uploading multiple files to server by FormData: ```dart final formData = FormData.fromMap({ 'name': 'dio', 'date': DateTime.now().toIso8601String(), 'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'), 'files': [ await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt'), await MultipartFile.fromFile('./text2.txt', filename: 'text2.txt'), ] }); final response = await dio.post('/info', data: formData); ``` Listening the uploading progress: ```dart final response = await dio.post( 'https://www.dtworkroom.com/doris/1/2.0.0/test', data: {'aa': 'bb' * 22}, onSendProgress: (int sent, int total) { print('$sent $total'); }, ); ``` Post binary data with Stream: ```dart // Binary data final postData = [0, 1, 2]; await dio.post( url, data: Stream.fromIterable(postData.map((e) => [e])), // Creates a Stream>. options: Options( headers: { Headers.contentLengthHeader: postData.length, // Set the content-length. }, ), ); ``` Note: `content-length` must be set if you want to subscribe to the sending progress. See all examples code [here](example). ## Dio APIs ### Creating an instance and set default configs. > It is recommended to use a singleton of `Dio` in projects, which can manage configurations like headers, base urls, > and timeouts consistently. > Here is an [example](../example_flutter_app) that use a singleton in Flutter. You can create instance of Dio with an optional `BaseOptions` object: ```dart final dio = Dio(); // With default `Options`. void configureDio() { // Set default configs dio.options.baseUrl = 'https://api.pub.dev'; dio.options.connectTimeout = Duration(seconds: 5); dio.options.receiveTimeout = Duration(seconds: 3); // Or create `Dio` with a `BaseOptions` instance. final options = BaseOptions( baseUrl: 'https://api.pub.dev', connectTimeout: Duration(seconds: 5), receiveTimeout: Duration(seconds: 3), ); final anotherDio = Dio(options); } ``` The core API in Dio instance is: ```dart Future> request( String path, { Object? data, Map? queryParameters, CancelToken? cancelToken, Options? options, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress, }); ``` ```dart final response = await dio.request( '/test', data: {'id': 12, 'name': 'dio'}, options: Options(method: 'GET'), ); ``` ### Request Options The `Options` class describes the http request information and configuration. Each Dio instance has a base config for all requests made by itself, and we can override the base config with `Options` when make a single request. The `Options` declaration as follows: ```dart /// Http method. String method; /// Request base url, it can contain sub path, like: https://dart.dev/api/. String? baseUrl; /// Http request headers. Map? headers; /// Timeout for opening url. Duration? connectTimeout; /// Whenever more than [receiveTimeout] passes between two events from response stream, /// [Dio] will throw the [DioException] with [DioExceptionType.RECEIVE_TIMEOUT]. /// Note: This is not the receiving time limitation. Duration? receiveTimeout; /// Request data, can be any type. dynamic data; /// If the `path` starts with 'http(s)', the `baseURL` will be ignored, otherwise, /// it will be combined and then resolved with the baseUrl. String path; /// The request Content-Type. /// /// The default `content-type` for requests will be implied by the /// [ImplyContentTypeInterceptor] according to the type of the request payload. /// The interceptor can be removed by /// [Interceptors.removeImplyContentTypeInterceptor]. /// /// If you want to encode request body with 'application/x-www-form-urlencoded', /// you can set [Headers.formUrlEncodedContentType], and [Dio] /// will automatically encode the request body. String? contentType; /// [responseType] indicates the type of data that the server will respond with /// options which defined in [ResponseType] are `json`, `stream`, `plain`. /// /// The default value is `json`, dio will parse response string to json object automatically /// when the content-type of response is 'application/json'. /// /// If you want to receive response data with binary bytes, for example, /// downloading a image, use `stream`. /// /// If you want to receive the response data with String, use `plain`. ResponseType? responseType; /// `validateStatus` defines whether the request is successful for a given /// HTTP response status code. If `validateStatus` returns `true` , /// the request will be perceived as successful; otherwise, considered as failed. ValidateStatus? validateStatus; /// Custom field that you can retrieve it later in /// [Interceptor], [Transformer] and the [Response] object. Map? extra; /// Common query parameters. Map*/ >? queryParameters; /// [listFormat] indicates the format of collection data in request options /// The default value is `multiCompatible` ListFormat? listFormat; ``` There is a complete example [here](../example/lib/options.dart). ### Response The response for a request contains the following information. ```dart /// Response body. may have been transformed, please refer to [ResponseType]. T? data; /// The corresponding request info. RequestOptions requestOptions; /// HTTP status code. int? statusCode; /// Returns the reason phrase associated with the status code. /// The reason phrase must be set before the body is written /// to. Setting the reason phrase after writing to the body. String? statusMessage; /// Whether this response is a redirect. /// ** Attention **: Whether this field is available depends on whether the /// implementation of the adapter supports it or not. bool isRedirect; /// The series of redirects this connection has been through. The list will be /// empty if no redirects were followed. [redirects] will be updated both /// in the case of an automatic and a manual redirect. /// /// ** Attention **: Whether this field is available depends on whether the /// implementation of the adapter supports it or not. List redirects; /// Custom fields that are constructed in the [RequestOptions]. Map extra; /// Response headers. Headers headers; ``` When request is succeed, you will receive the response as follows: ```dart final response = await dio.get('https://pub.dev'); print(response.data); print(response.headers); print(response.requestOptions); print(response.statusCode); ``` ### Interceptors For each dio instance, we can add one or more interceptors, by which we can intercept requests, responses, and errors before they are handled by `then` or `catchError`. ```dart dio.interceptors.add( InterceptorsWrapper( onRequest: (RequestOptions options, RequestInterceptorHandler handler) { // Do something before request is sent. // If you want to resolve the request with custom data, // you can resolve a `Response` using `handler.resolve(response)`. // If you want to reject the request with a error message, // you can reject with a `DioException` using `handler.reject(dioError)`. return handler.next(options); }, onResponse: (Response response, ResponseInterceptorHandler handler) { // Do something with response data. // If you want to reject the request with a error message, // you can reject a `DioException` object using `handler.reject(dioError)`. return handler.next(response); }, onError: (DioException e, ErrorInterceptorHandler handler) { // Do something with response error. // If you want to resolve the request with some custom data, // you can resolve a `Response` object using `handler.resolve(response)`. return handler.next(e); }, ), ); ``` Simple interceptor example: ```dart import 'package:dio/dio.dart'; class CustomInterceptors extends Interceptor { @override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { print('REQUEST[${options.method}] => PATH: ${options.path}'); super.onRequest(options, handler); } @override void onResponse(Response response, ResponseInterceptorHandler handler) { print('RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}'); super.onResponse(response, handler); } @override Future onError(DioException err, ErrorInterceptorHandler handler) async { print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}'); super.onError(err, handler); } } ``` #### Resolve and reject the request In all interceptors, you can interfere with their execution flow. If you want to resolve the request/response with some custom data, you can call `handler.resolve(Response)`. If you want to reject the request/response with a error message, you can call `handler.reject(dioError)` . ```dart dio.interceptors.add( InterceptorsWrapper( onRequest: (options, handler) { return handler.resolve( Response(requestOptions: options, data: 'fake data'), ); }, ), ); final response = await dio.get('/test'); print(response.data); // 'fake data' ``` #### QueuedInterceptor `Interceptor` can be executed concurrently, that is, all the requests enter the interceptor at once, rather than executing sequentially. However, in some cases we expect that requests enter the interceptor sequentially like #590. Therefore, we need to provide a mechanism for sequential access (step by step) to interceptors and `QueuedInterceptor` can solve this problem. ##### Example Because of security reasons, we need all the requests to set up a `csrfToken` in the header, if `csrfToken` does not exist, we need to request a csrfToken first, and then perform the network request, because the request csrfToken progress is asynchronous, so we need to execute this async request in request interceptor. For the complete code see [here](../example/lib/queued_interceptor_crsftoken.dart). #### LogInterceptor You can apply the `LogInterceptor` to log requests and responses automatically in the DEBUG mode: ```dart dio.interceptors.add(LogInterceptor(responseBody: false)); // Do not output responses body. ``` **Note:** `LogInterceptor` should be ... ...

近期下载者

相关文件


收藏者