dio 是一个强大的 HTTP 网络请求库,支持全局配置、Restful API、FormData、拦截器、 请求取消、Cookie 管理、文件上传/下载、超时、自定义适配器、转换器等。
开始使用
将 dio 添加至 pubspec.yaml:
dependencies:
dio: ^替换为最新版本
简单的使用示例
import 'package:dio/dio.dart';
final dio = Dio();
void getHttp() async {
final response = await dio.get('https://dart.dev');
print(response);
}
简单的Get请求示例
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());
}
简单的Post请求示例
response = await dio.post('/test', data: {'id': 12, 'name': 'dio'});
发起多个并发请求
response = await Future.wait([dio.post('/info'), dio.get('/token')]);
下载文件
response = await dio.download(
'https://www.google.com/',
'${(await getTemporaryDirectory()).path}google.html',
);
发送 FormData
final formData = FormData.fromMap({
'name': 'dio',
'date': DateTime.now().toIso8601String(),
});
final response = await dio.post('/info', data: formData);
Options 配置项
/// 请求方式。
String method;
/// 请求基本地址,可以包含路径例如 https://dart.dev/api/。
String? baseUrl;
/// HTTP 请求头。
Map<String, dynamic>? headers;
/// 连接服务器超时时间.
Duration? connectTimeout;
/// 两次数据流数据接收的最长间隔时间,注意不是请求的最长接收时间。
Duration? receiveTimeout;
/// 请求内容体,可以是任意类型。
dynamic data;
/// 请求路径,如果以 http(s)开始, 则 [baseURL] 会被忽略,
/// 否则将会和 [baseUrl] 拼接出完整的地址。
String path = '';
/// 请求的 Content-Type。
///
/// 默认值会由 [ImplyContentTypeInterceptor] 根据请求载荷类型进行推导。
/// 可以调用 [Interceptors.removeImplyContentTypeInterceptor] 进行移除。
///
/// 如果你想以 `application/x-www-form-urlencoded` 格式编码请求数据,
/// 可以设置此选项为 `Headers.formUrlEncodedContentType`,
/// [Dio] 会自动编码请求体。
String? contentType;
/// 期望以哪种格式(方式)接受响应数据,包括 `json`、`stream` 和 `plain`。
///
/// 默认值是 `json`, 当响应头中 content-type 为 `application/json` 时,
/// dio 会自动将响应内容转化为 json 对象。
/// 如果想以二进制方式接受响应数据,如下载一个二进制文件,那么可以使用 `stream`。
///
/// 如果想以文本(字符串)格式接收响应数据,请使用 `plain`。
ResponseType? responseType;
/// `validateStatus` 决定 HTTP 响应状态码是否被视为请求成功,
/// 返回 `true` 请求结果就会按成功处理,否则会按失败处理.
ValidateStatus? validateStatus;
/// 用户自定义字段,可以在 [Interceptor]、[Transformer] 和 [Response] 中依次传递。
Map<String, dynamic>? extra;
/// 请求地址的参数。
Map<String, dynamic /*String|Iterable<String>*/ >? queryParameters;
/// 请求数据中数组的编码的方式,默认值为 `multiCompatible`。
ListFormat? listFormat;