当前位置:网站首页>Dio encapsulated by the flutter network request (cookie management, adding interceptors, downloading files, exception handling, canceling requests, etc.)
Dio encapsulated by the flutter network request (cookie management, adding interceptors, downloading files, exception handling, canceling requests, etc.)
2022-06-25 22:19:00 【InfoQ】
Dio relevant
- Add dependency , Be careful 3.0.+ Is an incompatible upgrade
dependencies:
dio: ^3.0.9
- A minimalist example
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.baidu.com");
print(response);
} catch (e) {
print(e);
}
}
Packaging begins
- Network requests are often used , So let's take a simple example , Create a new one called httpUtil The file of
class HttpUtil {
static HttpUtil instance;
Dio dio;
BaseOptions options;
CancelToken cancelToken = new CancelToken();
static HttpUtil getInstance() {
if (null == instance) instance = new HttpUtil();
return instance;
}
}
- Configure and initialize Dio
/*
* config it and create
*/
HttpUtil() {
//BaseOptions、Options、RequestOptions Parameters can be configured , The priority level increases in turn , And the parameters can be overridden according to the priority
options = new BaseOptions(
// Request base address , Can contain sub paths
baseUrl: "http://www.google.com",
// Connection server timeout , In milliseconds .
connectTimeout: 10000,
// The interval between the two received data on the response stream , The unit is millisecond .
receiveTimeout: 5000,
//Http Request header .
headers: {
//do something
"version": "1.0.0"
},
// Requested Content-Type, The default value is "application/json; charset=utf-8",Headers.formUrlEncodedContentType The request body is automatically encoded .
contentType: Headers.formUrlEncodedContentType,
// Indicates that you expect to ( The way ) Accept response data . Accept 4 Types `json`, `stream`, `plain`, `bytes`. The default value is `json`,
responseType: ResponseType.json,
);
dio = new Dio(options);
}
RequestOptions requestOptions=new RequestOptions(
baseUrl: "http://www.google.com/aa/bb/cc/"
);
get request
/*
* get request
*/
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 body
// response.headers; Response head
// response.request; Request body
// response.statusCode; Status code
} on DioError catch (e) {
print('get error---------$e');
formatError(e);
}
return response.data;
}
post request
/*
* post request
*/
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 Forms
FormData formData = FormData.from({
"name": "wendux",
"age": 25,
});
response = await dio.post("/info", data: formData);
exception handling
/*
* error Unified treatment
*/
void formatError(DioError e) {
if (e.type == DioErrorType.CONNECT_TIMEOUT) {
// It occurs when url is opened timeout.
print(" Connection timeout ");
} else if (e.type == DioErrorType.SEND_TIMEOUT) {
// It occurs when url is sent timeout.
print(" request timeout ");
} else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
//It occurs when receiving timeout
print(" Response timeout ");
} else if (e.type == DioErrorType.RESPONSE) {
// When the server response, but with a incorrect status, such as 404, 503...
print(" Something unusual happened ");
} else if (e.type == DioErrorType.CANCEL) {
// When the request is cancelled, dio will throw a error with this type.
print(" Request cancellation ");
} else {
//DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
print(" Unknown error ");
}
}
Cookie management
- rely on
dependencies:
dio_cookie_manager: ^1.0.0
- introduce
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
- Use
//Cookie management
dio.interceptors.add(CookieManager(CookieJar()));
Add interceptor
dio = new Dio(options);
// Add interceptor
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
print(" Request before ");
// Do something before request is sent
return options; //continue
}, onResponse: (Response response) {
print(" Before responding ");
// Do something with response data
return response; // continue
}, onError: (DioError e) {
print(" Before the mistake ");
// Do something with response error
return e; //continue
}));
Download the file
/*
* Download the file
*/
downloadFile(urlPath, savePath) async {
Response response;
try {
response = await dio.download(urlPath, savePath,onReceiveProgress: (int count, int total){
// speed of progress
print("$count $total");
});
print('downloadFile success---------${response.data}');
} on DioError catch (e) {
print('downloadFile error---------$e');
formatError(e);
}
return response.data;
}
Cancel the request
/*
* Cancel the request
*
* The same cancel token Can be used for multiple requests , When one cancel token On cancellation , All uses should be cancel token All requests will be cancelled .
* So the parameters are optional
*/
void cancelRequests(CancelToken token) {
token.cancel("cancelled");
}
Https Certificate verification
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;
};
Invoke the sample
var response = await HttpUtil().get("http://www.baidu.com");
print(response.toString());
Complete code
边栏推荐
- . Thoughts on software trends in the 20th anniversary of net
- InfiniBand& RDMA
- 聊聊Adapter模式
- CVPR2022教程 | 马里兰大学《机器学习遥感处理:农业与粮食安全》教程
- JS disable the browser PDF printing and downloading functions (pdf.js disable the printing and downloading functions)
- In depth analysis of Flink fine-grained resource management
- 挖财证券开户安全嘛?
- Research Report on China's new energy technology and equipment market competition analysis and marketing strategy suggestions 2022-2028
- Simulate ATM system (account opening, login, account query, withdrawal, deposit, transfer, password modification, account cancellation)
- After osx-kvm modifies EFI, oc: failed to load configuration, osx-kvm generates opencore Qcow2 reports an error, libguestfs: error: source '
猜你喜欢
Pycharm 2022.1 EAP 2 release

聊聊Adapter模式
![[WPF] XAML code skills that can be directly used for converting CAD engineering drawings to WPF](/img/50/bb9e73cb4eabcef4bee8f6d5b2fcb6.png)
[WPF] XAML code skills that can be directly used for converting CAD engineering drawings to WPF

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

Where is win11 screen recording data saved? Win11 screen recording data storage location

实验三的各种特效案例

About the version mismatch of unity resource package after importing the project

Exclusive interview with deepmindceo hassabis: we will see a new scientific Renaissance! AI's new achievements in nuclear fusion are officially announced today

What if win11 cannot delete the folder? Win11 cannot delete folder

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
随机推荐
【Proteus仿真】ArduinoUNO+数码管循环显示0~9
China soft magnetic material market demand status and prospect scale forecast report 2022-2028
Top in the whole network, it is no exaggeration to say that this Stanford machine learning tutorial in Chinese notes can help you learn from the beginning to the mastery of machine learning
Illustration de l'exécution du cadre de pile
图解栈帧运行过程
HNU network counting experiment: experiment I application protocol and packet analysis experiment (using Wireshark)
js禁用浏览器 pdf 打印、下载功能(pdf.js 禁用打印下载、功能)
HNU计网实验:实验一 应用协议与数据包分析实验(使用Wireshark)
Mastering quantization technology is the key to video compression
Open source optimized VVC encoder in general scenarios
Fujilai pharmaceutical has passed the registration: the annual revenue is nearly 500million yuan. Xiangyun once illegally traded foreign exchange
EVC, VVC, lcevc test: how about the performance of the latest MPEG codec?
Research on depth image compression in YUV420 color space
In depth analysis of Flink fine-grained resource management
JS disable the browser PDF printing and downloading functions (pdf.js disable the printing and downloading functions)
js 限制鼠标移动范围
Hard liver! Super detailed basic introduction to Matplotlib!!!
Research Report on China's new energy technology and equipment market competition analysis and marketing strategy suggestions 2022-2028
Flutter 网络请求封装之Dio(Cookie管理、添加拦截器、下载文件、异常处理、取消请求等)
Research and Analysis on the status quo of China's Cross lamp market and forecast report on its development prospect (2022)