当前位置:网站首页>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
边栏推荐
- 数据治理,说起来容易,做起来难
- 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
- Presto中Limit算子的处理过程
- be careful! This written examination method is gradually being replaced
- Report on development status and prospects of global and Chinese coating industry strategic planning proposal 2022-2028
- Huawei switch stack configuration
- Beyond natural motion: exploring the discontinuity of video interpolation
- Leetcode topic [array] -18- sum of four numbers
- To ensure the Beijing Winter Olympic Games, digital data gives a power without code!
- IAAs, PAAS, SaaS, baas, FAAS differences
猜你喜欢

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

Créer le premier site Web avec idea

Win11录屏数据保存在哪里?Win11录屏数据保存的位置
What is the difficulty of the form tool that costs billions of dollars? Exclusive interview with si no

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

Yyds dry goods inventory CEPH installation visual dashboard

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

Wd4t secondary opening firmware 190 module for mobile hard disk data recovery is successfully repaired

了解有哪几个C标准&了解C编译管道

InfiniBand& RDMA
随机推荐
What is a ZFS file system
Is it safe to open an account with Caicai securities?
SSH modifies grub in heiqunhui ds918+ system 7.0.1 cfg
Processing of limit operator in Presto
Illustration de l'exécution du cadre de pile
聊聊Adapter模式
Bear market guide | some essential lessons and specific survival rules
Devops之制品库平台nexus实践
Practice of product library platform nexus of Devops
了解有哪几个C标准&了解C编译管道
Market depth analysis and development strategy consulting report of China's fire equipment market 2022-2028
Pat 1083 list grades (25 points)
Measurement fitting based on Halcon learning -- Practice [2]
InfiniBand& RDMA
. Thoughts on software trends in the 20th anniversary of net
HNU network counting experiment: experiment I application protocol and packet analysis experiment (using Wireshark)
ASP. Net core uses function switches to control Route Access (Continued) yyds dry inventory
Yyds dry goods inventory CEPH installation visual dashboard
China bed and mattress market status research analysis and development prospect forecast report (2022)
Youku IPv6 evolution and Practice Guide