dio 框架介紹
A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc
基于 Dart 語言編寫的強(qiáng)大的網(wǎng)絡(luò)請求框架铃辖,支持?jǐn)r截器忠售,全局配置,F(xiàn)ormData昌罩,請求取消肄方,文件下載稚矿,超時(shí)監(jiān)聽等
dio 項(xiàng)目應(yīng)用
首先在 pubspec.yaml 文件中添加 dio 庫依賴并 Packages get
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
dio: ^2.1.5
然后封裝基于 dio 框架的 http 請求工具類
import 'package:dio/dio.dart';
/**
* @des Dio 網(wǎng)絡(luò)請求框架工具類
* @author liyongli 20190523
* */
class DioHttpUtils{
// 服務(wù)器接口地址公有部分
final _httpBaseUrl = "https://www.xxx...";
// 請求超時(shí)時(shí)長
final _httpConnectTimeout = 10000;
// 接收超時(shí)時(shí)長
final _hpptReceiveTimeout = 10000;
// 本類實(shí)例
static DioHttpUtils _dioHttpUtilsObject;
// 請求實(shí)例
static Dio _dioObject;
// 參數(shù)實(shí)例
static BaseOptions _baseOptionsObject;
/// 單例訪問
static DioHttpUtils getInstance(){
if(null == _dioHttpUtilsObject){
_dioHttpUtilsObject = new DioHttpUtils._();
}
return _dioHttpUtilsObject;
}
/// 私有化構(gòu)造(單例模式)
DioHttpUtils._(){
// 初始化 http 基本設(shè)置
_baseOptionsObject =new BaseOptions(
baseUrl: _httpBaseUrl,
connectTimeout: _httpConnectTimeout,
receiveTimeout: _hpptReceiveTimeout,
headers: {}
);
// 定義請求實(shí)例
_dioObject = new Dio(_baseOptionsObject);
// 添加請求事件監(jiān)聽
_dioObject.interceptors.add(InterceptorsWrapper(
// 攔截請求發(fā)送事件(如添加 token掏熬、versionCode搀崭、platformType 等)
onRequest: (RequestOptions options){
// do something
return options;
},
// 攔截請求響應(yīng)事件(如數(shù)據(jù)重組叨粘,便于業(yè)務(wù)代碼中快速處理調(diào)用)
onResponse: (Response response){
// do something
return response;
},
// 攔截請求失敗事件(如添加統(tǒng)一的錯(cuò)誤提示 或 統(tǒng)一的錯(cuò)誤處理邏輯等)
onError: (DioError error){
return error;
}
));
}
/// get 請求
get(url,{ options, cancelToken, parameters=null}) async {
Response response;
try{
response = await _dioObject.get(url, queryParameters:parameters, cancelToken:cancelToken);
}on DioError catch(e){
if(CancelToken.isCancel(e)){
print('請求取消:' + e.message);
}else{
print('請求錯(cuò)誤:$e');
}
}
return response.data;
}
/// post請求
post(url,{ options, cancelToken, parameters=null}) async {
Response response;
try{
response = await _dioObject.post(url, queryParameters:parameters !=null ? parameters : {}, cancelToken:cancelToken);
print(response);
}on DioError catch(e){
if(CancelToken.isCancel(e)){
print('請求取消:' + e.message);
}else{
print('請求錯(cuò)誤:$e');
}
}
return response.data;
}
}
調(diào)用方式
DioHttpUtils.getInstance().get("url", parameters: "");
DioHttpUtils.getInstance().post("url", parameters: "");
本篇到此完結(jié),更多 Flutter 跨平臺移動端開發(fā) 原創(chuàng)內(nèi)容持續(xù)更新中~
期待您 關(guān)注 / 點(diǎn)贊 / 收藏 向著 大前端工程師 晉級瘤睹!