dio是一個(gè)強(qiáng)大的Dart Http請(qǐng)求庫(kù),支持Restful API涉波、FormData英上、攔截器、請(qǐng)求取消啤覆、Cookie管理苍日、文件上傳/下載、超時(shí)窗声、自定義適配器等相恃。本文是基于dio庫(kù)的簡(jiǎn)單二次封裝,以適應(yīng)我們平常開發(fā)中常用的get請(qǐng)求和post請(qǐng)求笨觅。
添加依賴
dependencies:
dio: ^2.1.0
dio封裝
首先拦耐,對(duì)dio進(jìn)行初始化耕腾。這里使用工廠構(gòu)造函數(shù)創(chuàng)建DioUtil,在Dart中杀糯,當(dāng)實(shí)現(xiàn)一個(gè)使用 factory 關(guān)鍵詞修飾的構(gòu)造函數(shù)時(shí)扫俺,這個(gè)構(gòu)造函數(shù)不必創(chuàng)建類的新實(shí)例。
static final DioUtil _instance = DioUtil._init();
static Dio _dio;
factory DioUtil() {
return _instance;
}
DioUtil._init() {
_dio = new Dio();
}
設(shè)置BaseOptions參數(shù)固翰,可以設(shè)置網(wǎng)絡(luò)請(qǐng)求超時(shí)時(shí)間狼纬,設(shè)置baseUrl。dio默認(rèn)請(qǐng)求contentType為application/json骂际,如果需要設(shè)置為application/x-www-form-urlencoded疗琉,需在BaseOptions中單獨(dú)設(shè)置。在BaseOptions.hearders中可以添加自定義的網(wǎng)絡(luò)請(qǐng)求頭信息歉铝。
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<String, dynamic> headers = Map<String, dynamic>();
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;
}
網(wǎng)絡(luò)請(qǐng)求過(guò)程
- path 請(qǐng)求path路徑盈简,這里我們進(jìn)行了restful請(qǐng)求處理,path路徑參數(shù)放在pathParams中犯戏。
- method 請(qǐng)求方式送火,可以為GET、POST先匪、PUT种吸、HEAD、DELETE呀非、PATCH等坚俗,這字我們僅展示GET請(qǐng)求和POST請(qǐng)求。
- pathParams path路徑參數(shù)岸裙,Map數(shù)據(jù)結(jié)構(gòu)
- errorCallback 自定義錯(cuò)誤處理猖败,代碼中_handleHttpError()方法進(jìn)行統(tǒng)一的http錯(cuò)誤碼處理,如接口需單獨(dú)處理某種錯(cuò)誤碼降允,可添加此回調(diào)方法恩闻。
返回?cái)?shù)據(jù)如果為Map數(shù)據(jù)直接返回,如果為Json數(shù)據(jù)需通過(guò)json.decode解析之后再返回剧董。
Future<Map<String, dynamic>> request(String path,{String method, Map pathParams, data, Function errorCallback}) async {
///restful請(qǐng)求處理
if(pathParams != null) {
pathParams.forEach((key, value) {
if(path.indexOf(key) != -1) {
path = path.replaceAll(":$key", value.toString());
}
});
}
Response response = await _dio.request(path, data: data, options: Options(method: method));
if(response.statusCode == HttpStatus.ok || response.statusCode == HttpStatus.created) {
try {
if(response.data is Map) {
return response.data;
} else {
return json.decode(response.data.toString());
}
} catch(e) {
return null;
}
} else {
_handleHttpError(response.statusCode);
if(errorCallback != null) {
errorCallback(response.statusCode);
}
return null;
}
}
GET請(qǐng)求
Future<Map<String, dynamic>> get(String path, {pathParams, data, Function errorCallback}) {
return request(path, method: Method.get, pathParams: pathParams, data: data, errorCallback: errorCallback);
}
POST請(qǐng)求
Future<Map<String, dynamic>> post(String path, {pathParams, data, Function errorCallback}) {
return request(path, method: Method.post, pathParams: pathParams, data: data, errorCallback: errorCallback);
}
完整代碼
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<String, dynamic> headers = Map<String, dynamic>();
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<Map<String, dynamic>> get(String path, {pathParams, data, Function errorCallback}) {
return request(path, method: Method.get, pathParams: pathParams, data: data, errorCallback: errorCallback);
}
Future<Map<String, dynamic>> post(String path, {pathParams, data, Function errorCallback}) {
return request(path, method: Method.post, pathParams: pathParams, data: data, errorCallback: errorCallback);
}
Future<Map<String, dynamic>> request(String path,{String method, Map pathParams, data, Function errorCallback}) async {
///restful請(qǐng)求處理
if(pathParams != null) {
pathParams.forEach((key, value) {
if(path.indexOf(key) != -1) {
path = path.replaceAll(":$key", value.toString());
}
});
}
Response response = await _dio.request(path, data: data, options: Options(method: method));
if(response.statusCode == HttpStatus.ok || response.statusCode == HttpStatus.created) {
try {
if(response.data is Map) {
return response.data;
} else {
return json.decode(response.data.toString());
}
} catch(e) {
return null;
}
} else {
_handleHttpError(response.statusCode);
if(errorCallback != null) {
errorCallback(response.statusCode);
}
return null;
}
}
///處理Http錯(cuò)誤碼
void _handleHttpError(int errorCode) {
}
}
示例
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');
});