dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等。本文是基于dio库的简单二次封装,以适应我们平常开发中常用的get请求和post请求。
dependencies:
dio: ^2.1.0
首先,对dio进行初始化。这里使用工厂构造函数创建DioUtil,在Dart中,当实现一个使用 factory 关键词修饰的构造函数时,这个构造函数不必创建类的新实例。
static final DioUtil _instance = DioUtil._init();
static Dio _dio;
factory DioUtil() {
return _instance;
}
DioUtil._init() {
_dio = new Dio();
}
设置BaseOptions参数,可以设置网络请求超时时间,设置baseUrl。dio默认请求contentType为application/json,如果需要设置为application/x-www-form-urlencoded,需在BaseOptions中单独设置。在BaseOptions.hearders中可以添加自定义的网络请求头信息。
static BaseOptions getDefOptions() {
BaseOptions options = BaseOptions();
options.connectTimeout = 10 * 1000;
options.receiveTimeout = 20 * 1000;
options.baseUrl = ‘ http://www.mocky.io/)’
options.contentType = ContentType.parse('application/x-www-form-urlencoded');
Map headers = Map();
headers['Accept'] = 'application/json';
String platform;
if(Platform.isAndroid) {
platform = "Android";
} else if(Platform.isIOS) {
platform = "IOS";
}
headers['OS'] = platform;
options.headers = headers;
return options;
}
setOptions(BaseOptions options) {
_options = options;
_dio.options = _options;
}
网络请求过程
返回数据如果为Map数据直接返回,如果为Json数据需通过json.decode解析之后再返回。
Future
GET请求
Future
POST请求
Future
完整代码
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
class Method {
static final String get = "GET";
static final String post = "POST";
static final String put = "PUT";
static final String head = "HEAD";
static final String delete = "DELETE";
static final String patch = "PATCH";
}
class DioUtil {
static final DioUtil _instance = DioUtil._init();
static Dio _dio;
static BaseOptions _options = getDefOptions();
factory DioUtil() {
return _instance;
}
DioUtil._init() {
_dio = new Dio();
}
static BaseOptions getDefOptions() {
BaseOptions options = BaseOptions();
options.connectTimeout = 10 * 1000;
options.receiveTimeout = 20 * 1000;
options.contentType = ContentType.parse('application/x-www-form-urlencoded');
Map headers = Map();
headers['Accept'] = 'application/json';
String platform;
if(Platform.isAndroid) {
platform = "Android";
} else if(Platform.isIOS) {
platform = "IOS";
}
headers['OS'] = platform;
options.headers = headers;
return options;
}
setOptions(BaseOptions options) {
_options = options;
_dio.options = _options;
}
Future
DioUtil().get('v2/5ca06a7d3300007200a87e01/:id',
pathParams: {
':id': 12
},
data: {
'name':'tony',
'age': 23
},
errorCallback: (statusCode) {
print('Http error code : $statusCode');
}
).then((data) {
print('Http response: $data');
});