文章目录
官方文档:
https://github.com/flutterchina/dio/blob/master/README-ZH.md
由于flutter目前的http请求功能相对比较单一,所以推荐一款flutter中网络请求的三方库,这个也是官方推荐的库,口碑不错,可以研究。
使用Dio的配置
默认配置
// ①使用默认配置
Dio dio = new Dio();
// 配置dio实例
dio.options.baseUrl = 'https://www.wanandroid.com/';
dio.options.connectTimeout = 5000;
dio.options.receiveTimeout = 3000;
通过options配置
// ②通过传递一个 `options`来创建dio实例
BaseOptions options = new BaseOptions(
baseUrl: 'https://www.wanandroid.com/',
connectTimeout: 5000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);
GET 请求
// response = await dio.get('article/list/0/json?cid=60');
// 或者
response = await dio.get('article/list/0/json', queryParameters: {"cid": 60});
print(response.data.toString());
POST请求
response = await dio.post("test", data: {"id": 12, "name": "blissyang"});
多个并发请求:
response = Future.wait([dio.post('info'), dio.get('token')]) as Response;
下载文件
response = await dio.download('https://www.google.com/', './by.html',
onReceiveProgress: (int count, int total) {
//下载文件的进度监听
print('$count $total');
});
以流的方式接收响应数据:
Response<List<int>> rs = await Dio().get<List<int>>(
url,
options: Options(responseType: ResponseType.bytes), //设置接收类型为bytes
);
print(rs.data);
发送表单请求 FormData:
FormData formData = new FormData.from({
"name": "blissyang",
'age': 25,
});
response = await dio.post('info', data: formData);
通过FormData上传多个文件:
FormData formData1 = new FormData.from({
'name': 'blissyang',
'age': 28,
'file1': new UploadFileInfo(new File('./upload.txt'), 'upload.txt'),
// 支持直接上传字节数组 (List<int>) ,方便直接上传内存中的内容
'file2':
new UploadFileInfo.fromBytes(utf8.encode('hello world'), 'word.txt'),
'files': [
new UploadFileInfo(new File('./example/upload.txt'), 'upload.txt'),
new UploadFileInfo(new File('./example/upload.txt'), 'upload.txt'),
]
});
response = await dio.post('info', data: formData1);
监听发送(上传)数据进度:
response = await dio.post("http://www.dtworkroom.com/doris/1/2.0.0/test",
data: {"aa": "bb" * 22}, onSendProgress: (int sent, int total) {
print('$sent $total');
});
以流的形式提交二进制数据:
// 二进制数据
List<int> postData = <int>[];
await dio.post(
url,
data: Stream.fromIterable(postData.map((e) => [e])),//创建一个Stream<List<int>>
options: Options(
headers: {
HttpHeaders.contentLengthHeader:postData.length,// 设置content-length
// 如果要监听提交进度,则必须设置content-length,反之则是可选的。
}
)
);