当前位置:网站首页>Flutter 網絡請求封裝之Dio(Cookie管理、添加攔截器、下載文件、异常處理、取消請求等)
Flutter 網絡請求封裝之Dio(Cookie管理、添加攔截器、下載文件、异常處理、取消請求等)
2022-06-25 22:19:00 【InfoQ】
Dio相關
- 添加依賴,注意3.0.+是不兼容昇級
dependencies:
dio: ^3.0.9
- 一個極簡示例
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.baidu.com");
print(response);
} catch (e) {
print(e);
}
}
封裝開始
- 網絡請求是經常會用到的,所以直接來一個單例,新建一個名為httpUtil的文件
class HttpUtil {
static HttpUtil instance;
Dio dio;
BaseOptions options;
CancelToken cancelToken = new CancelToken();
static HttpUtil getInstance() {
if (null == instance) instance = new HttpUtil();
return instance;
}
}
- 配置和初始化Dio
/*
* config it and create
*/
HttpUtil() {
//BaseOptions、Options、RequestOptions 都可以配置參數,優先級別依次遞增,且可以根據優先級別覆蓋參數
options = new BaseOptions(
//請求基地址,可以包含子路徑
baseUrl: "http://www.google.com",
//連接服務器超時時間,單比特是毫秒.
connectTimeout: 10000,
//響應流上前後兩次接受到數據的間隔,單比特為毫秒。
receiveTimeout: 5000,
//Http請求頭.
headers: {
//do something
"version": "1.0.0"
},
//請求的Content-Type,默認值是"application/json; charset=utf-8",Headers.formUrlEncodedContentType會自動編碼請求體.
contentType: Headers.formUrlEncodedContentType,
//錶示期望以那種格式(方式)接受響應數據。接受4種類型 `json`, `stream`, `plain`, `bytes`. 默認值是 `json`,
responseType: ResponseType.json,
);
dio = new Dio(options);
}
RequestOptions requestOptions=new RequestOptions(
baseUrl: "http://www.google.com/aa/bb/cc/"
);
get請求
/*
* get請求
*/
get(url, {data, options, cancelToken}) async {
Response response;
try {
response = await dio.get(url, queryParameters: data, options: options, cancelToken: cancelToken);
print('get success---------${response.statusCode}');
print('get success---------${response.data}');
// response.data; 響應體
// response.headers; 響應頭
// response.request; 請求體
// response.statusCode; 狀態碼
} on DioError catch (e) {
print('get error---------$e');
formatError(e);
}
return response.data;
}
post請求
/*
* post請求
*/
post(url, {data, options, cancelToken}) async {
Response response;
try {
response = await dio.post(url, queryParameters: data, options: options, cancelToken: cancelToken);
print('post success---------${response.data}');
} on DioError catch (e) {
print('post error---------$e');
formatError(e);
}
return response.data;
}
post Form錶單
FormData formData = FormData.from({
"name": "wendux",
"age": 25,
});
response = await dio.post("/info", data: formData);
异常處理
/*
* error統一處理
*/
void formatError(DioError e) {
if (e.type == DioErrorType.CONNECT_TIMEOUT) {
// It occurs when url is opened timeout.
print("連接超時");
} else if (e.type == DioErrorType.SEND_TIMEOUT) {
// It occurs when url is sent timeout.
print("請求超時");
} else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
//It occurs when receiving timeout
print("響應超時");
} else if (e.type == DioErrorType.RESPONSE) {
// When the server response, but with a incorrect status, such as 404, 503...
print("出現异常");
} else if (e.type == DioErrorType.CANCEL) {
// When the request is cancelled, dio will throw a error with this type.
print("請求取消");
} else {
//DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
print("未知錯誤");
}
}
Cookie管理
- 依賴
dependencies:
dio_cookie_manager: ^1.0.0
- 引入
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
- 使用
//Cookie管理
dio.interceptors.add(CookieManager(CookieJar()));
添加攔截器
dio = new Dio(options);
//添加攔截器
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
print("請求之前");
// Do something before request is sent
return options; //continue
}, onResponse: (Response response) {
print("響應之前");
// Do something with response data
return response; // continue
}, onError: (DioError e) {
print("錯誤之前");
// Do something with response error
return e; //continue
}));
下載文件
/*
* 下載文件
*/
downloadFile(urlPath, savePath) async {
Response response;
try {
response = await dio.download(urlPath, savePath,onReceiveProgress: (int count, int total){
//進度
print("$count $total");
});
print('downloadFile success---------${response.data}');
} on DioError catch (e) {
print('downloadFile error---------$e');
formatError(e);
}
return response.data;
}
取消請求
/*
* 取消請求
*
* 同一個cancel token 可以用於多個請求,當一個cancel token取消時,所有使用該cancel token的請求都會被取消。
* 所以參數可選
*/
void cancelRequests(CancelToken token) {
token.cancel("cancelled");
}
Https證書校驗
String PEM="XXXXX"; // certificate content
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
client.badCertificateCallback=(X509Certificate cert, String host, int port){
if(cert.pem==PEM){ // Verify the certificate
return true;
}
return false;
};
};
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
SecurityContext sc = new SecurityContext();
//file is the path of certificate
sc.setTrustedCertificates(file);
HttpClient httpClient = new HttpClient(context: sc);
return httpClient;
};
調用示例
var response = await HttpUtil().get("http://www.baidu.com");
print(response.toString());
完整代碼
边栏推荐
- Yyds dry goods inventory CEPH installation visual dashboard
- 聊聊Adapter模式
- Practice of product library platform nexus of Devops
- Research and Analysis on the status quo of China's Cross lamp market and forecast report on its development prospect (2022)
- 剖析虚幻渲染体系(16)- 图形驱动的秘密
- 北工大毕业时用的一些网址
- Wd4t secondary opening firmware 190 module for mobile hard disk data recovery is successfully repaired
- Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
- IAAs, PAAS, SaaS, baas, FAAS differences
- SOCKET编程部分I/O的初步解决
猜你喜欢

NARI radar's IPO meeting: it plans to raise nearly 1billion yuan. Bao Xiaojun and his wife are Canadians

ASP. Net core uses function switches to control Route Access (Continued) yyds dry inventory

【WPF】CAD工程图纸转WPF可直接使用的xaml代码技巧

Fujilai pharmaceutical has passed the registration: the annual revenue is nearly 500million yuan. Xiangyun once illegally traded foreign exchange

数字图像处理知识点总结概述
No nonsense, code practice will help you master strong caching and negotiation caching!

Simulate ATM system (account opening, login, account query, withdrawal, deposit, transfer, password modification, account cancellation)

JS disable the browser PDF printing and downloading functions (pdf.js disable the printing and downloading functions)

面对AI人才培养的“产学研”鸿沟,昇腾AI如何做厚产业人才黑土地?

Free cloud function proxy IP pool just released
随机推荐
Research and Analysis on the status quo of China's Cross lamp market and forecast report on its development prospect (2022)
Fujilai pharmaceutical has passed the registration: the annual revenue is nearly 500million yuan. Xiangyun once illegally traded foreign exchange
[proteus simulation] Arduino uno+ key controls 2-bit digital tube countdown
Research and Analysis on the current situation of Chinese acne drug market and forecast report on its development prospect (2022)
Opentelemetry architecture and terminology Introduction (Continued)
[proteus simulation] arduinouno+ digital tube cycle display 0~9
[intensive lecture] 2022 PHP intermediate and advanced interview questions (II)
Win11开始菜单右键空白?Win11开始菜单右键没反应解决方法
Research and Analysis on the current situation of China's magnetic detector Market and forecast report on its development prospect (2022)
【Proteus仿真】Arduino UNO+按键控制2位数码管倒计时
Introduction to HNU database system ODBC
[HNU summer semester] preparation stage of database system design
Windows11 windows security center cannot open Windows Defender cannot open
Dialog+: Audio dialogue enhancement technology based on deep learning
Application runtime layotto enters CNCF cloud native panorama
[WPF] XAML code skills that can be directly used for converting CAD engineering drawings to WPF
HLS. JS: past, present and future
Practice of product library platform nexus of Devops
Preliminary solution of i/o in socket programming
js禁用浏览器 pdf 打印、下载功能(pdf.js 禁用打印下载、功能)