当前位置:网站首页>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());
完整代码
边栏推荐
- Generic cmaf container for efficient cross format low latency delivery
- leetcode: 49. Grouping of alphabetic words
- Summary of basic knowledge of neural network
- Research and Analysis on the status quo of China's Cross lamp market and forecast report on its development prospect (2022)
- Apache uses setenvif to identify and release the CDN traffic according to the request header, intercept the DDoS traffic, pay attention to the security issues during CDN deployment, and bypass the CDN
- Free cloud function proxy IP pool just released
- Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
- Win11录屏数据保存在哪里?Win11录屏数据保存的位置
- Youku IPv6 evolution and Practice Guide
- Processing of limit operator in Presto
猜你喜欢
Evaluate the generalization performance of models and build integrated models using out of pocket prediction (oof)
Win11录屏数据保存在哪里?Win11录屏数据保存的位置
Obsidian基础教程
To ensure the Beijing Winter Olympic Games, digital data gives a power without code!
CVPR2022教程 | 马里兰大学《机器学习遥感处理:农业与粮食安全》教程
Créer le premier site Web avec idea
org. apache. ibatis. exceptions. PersistenceException:
Various special effect cases of Experiment 3
Build the first website with idea
be careful! This written examination method is gradually being replaced
随机推荐
Obsidian basic tutorial
SwiftUI 4 新功能 之 网格视图Gridview组件 (教程含源码)
了解有哪几个C标准&了解C编译管道
Type conversion basis
idea怎么把自己的项目打包成jar包
Pat 1083 list grades (25 points)
Research and Analysis on the current situation of China's magnetic detector Market and forecast report on its development prospect (2022)
leetcode: 49. 字母异位词分组
【hnu暑学期】数据库系统设计 准备阶段
Zhiyun health is about to go public: long-term losses, meinian health Yu Rong has withdrawn, and it is difficult to be optimistic about the future
图解栈帧运行过程
Mathematical analysis_ Notes_ Chapter 4: continuous function classes and other function classes
[proteus simulation] Arduino uno+ key controls 2-bit digital tube countdown
HNU计网实验:实验一 应用协议与数据包分析实验(使用Wireshark)
Winget: the "Winget" item cannot be recognized as the name of cmdlet, function, script file or runnable program. Win11 Winget cannot be used to solve this problem
Zero Trust: break the passive development mode of "attack and defense" and build a "moat" for enterprise safety
What is a code baseline?
Conglin environmental protection IPO meeting: annual profit of more than 200million to raise 2.03 billion
Various special effect cases of Experiment 3
智云健康上市在即:长期亏损,美年健康俞熔已退出,未来难言乐观