当前位置:网站首页>Flutter 网络请求封装之Dio(Cookie管理、添加拦截器、下载文件、异常处理、取消请求等)
Flutter 网络请求封装之Dio(Cookie管理、添加拦截器、下载文件、异常处理、取消请求等)
2022-06-25 21:44: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());
完整代码
边栏推荐
- Mastering quantization technology is the key to video compression
- Introduction to HLS content diversion and insert advertising specification
- Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
- 圖解棧幀運行過程
- Zhihu Gaozan: what ability is important, but most people don't have it?
- Introduction to HNU database system ODBC
- What is a ZFS file system
- How can the computer tablet be connected to the computer
- China coated abrasive tools industry market depth analysis and development strategy consulting report 2022-2028
- How does idea package its own projects into jar packages
猜你喜欢

Summary of basic knowledge of neural network

Sqlmap learning (sqli labs as an example)
In depth analysis of Flink fine-grained resource management

Conglin environmental protection IPO meeting: annual profit of more than 200million to raise 2.03 billion

Win11无法删除文件夹怎么办?Win11无法删除文件夹的解决方法
. Thoughts on software trends in the 20th anniversary of net

圖解棧幀運行過程

Illustration de l'exécution du cadre de pile

Obsidian基础教程

“No bean named ‘UserController‘ available“
随机推荐
Youku IPv6 evolution and Practice Guide
Exclusive interview with deepmindceo hassabis: we will see a new scientific Renaissance! AI's new achievements in nuclear fusion are officially announced today
数字图像处理知识点总结概述
How can the computer tablet be connected to the computer
Application runtime layotto enters CNCF cloud native panorama
Modprobe: fatal: module kvmgt not found, kvmgt has no module, kvmgt has no driver, gvt-g precautions, gvt-g precautions for starting win10 in UEFI mode
Win11无法删除文件夹怎么办?Win11无法删除文件夹的解决方法
Type conversion basis
Pat 1050 string subtraction (20 points) string find
be careful! This written examination method is gradually being replaced
leetcode: 49. 字母异位词分组
Circular structure and circular keywords
Research and Analysis on the current situation of Chinese acne drug market and forecast report on its development prospect (2022)
Preliminary solution of i/o in socket programming
图解栈帧运行过程
HNU network counting experiment: Experiment 4 application layer and transport layer protocol analysis (packettracer)
What is the difficulty of the form tool that costs billions of dollars? Exclusive interview with si no
智云健康上市在即:长期亏损,美年健康俞熔已退出,未来难言乐观
How to use Matplotlib library to realize enlarged display of graphic local data
How does idea package its own projects into jar packages