当前位置:网站首页>Dio encapsulé pour les requêtes réseau flutter (gestion des cookies, ajout d'intercepteurs, téléchargement de fichiers, gestion des exceptions, annulation des requêtes, etc.)
Dio encapsulé pour les requêtes réseau flutter (gestion des cookies, ajout d'intercepteurs, téléchargement de fichiers, gestion des exceptions, annulation des requêtes, etc.)
2022-06-25 22:19:00 【InfoQ】
DioAutres
- Ajouter une dépendance,Attention!3.0.+Est une mise à jour incompatible
dependencies:
dio: ^3.0.9
- Un exemple minimaliste
import 'package:dio/dio.dart';
void getHttp() async {
try {
Response response = await Dio().get("http://www.baidu.com");
print(response);
} catch (e) {
print(e);
}
}
Début de l'emballage
- Les demandes de réseau sont souvent utilisées,Donc, juste un exemple,Créer un nouveau nomhttpUtilDocuments
class HttpUtil {
static HttpUtil instance;
Dio dio;
BaseOptions options;
CancelToken cancelToken = new CancelToken();
static HttpUtil getInstance() {
if (null == instance) instance = new HttpUtil();
return instance;
}
}
- Configuration et initialisationDio
/*
* config it and create
*/
HttpUtil() {
//BaseOptions、Options、RequestOptions Vous pouvez configurer les paramètres , Les niveaux de priorité augmentent successivement , Et peut outrepasser les paramètres en fonction du niveau de priorité
options = new BaseOptions(
//Adresse de base demandée,Peut contenir des sous - Chemins
baseUrl: "http://www.google.com",
//Délai de connexion au serveur,En millisecondes.
connectTimeout: 10000,
// L'intervalle entre la réception des données avant et après le flux de réponse ,En millisecondes.
receiveTimeout: 5000,
//HttpEn - tête de la demande.
headers: {
//do something
"version": "1.0.0"
},
//DemandeContent-Type,La valeur par défaut est"application/json; charset=utf-8",Headers.formUrlEncodedContentType Le corps de la demande est automatiquement encodé .
contentType: Headers.formUrlEncodedContentType,
//Indique les attentes dans ce format(Comment)Accepter les données de réponse.Accepté4Type d'espèce `json`, `stream`, `plain`, `bytes`. La valeur par défaut est `json`,
responseType: ResponseType.json,
);
dio = new Dio(options);
}
RequestOptions requestOptions=new RequestOptions(
baseUrl: "http://www.google.com/aa/bb/cc/"
);
getDemande
/*
* getDemande
*/
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; Corps de réponse
// response.headers; En - tête de réponse
// response.request; Corps demandeur
// response.statusCode; Code d'état
} on DioError catch (e) {
print('get error---------$e');
formatError(e);
}
return response.data;
}
postDemande
/*
* postDemande
*/
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 FormFormulaire
FormData formData = FormData.from({
"name": "wendux",
"age": 25,
});
response = await dio.post("/info", data: formData);
Gestion des exceptions
/*
* errorTraitement uniforme
*/
void formatError(DioError e) {
if (e.type == DioErrorType.CONNECT_TIMEOUT) {
// It occurs when url is opened timeout.
print("Délai de connexion");
} else if (e.type == DioErrorType.SEND_TIMEOUT) {
// It occurs when url is sent timeout.
print("Délai de demande");
} else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
//It occurs when receiving timeout
print("Délai de réponse");
} else if (e.type == DioErrorType.RESPONSE) {
// When the server response, but with a incorrect status, such as 404, 503...
print("Une exception s'est produite");
} else if (e.type == DioErrorType.CANCEL) {
// When the request is cancelled, dio will throw a error with this type.
print("Demande d'annulation");
} else {
//DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
print("Erreur inconnue");
}
}
CookieGestion
- Dépendance
dependencies:
dio_cookie_manager: ^1.0.0
- Introduction
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
- Utiliser
//CookieGestion
dio.interceptors.add(CookieManager(CookieJar()));
Ajouter un intercepteur
dio = new Dio(options);
//Ajouter un intercepteur
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
print("Avant la demande");
// Do something before request is sent
return options; //continue
}, onResponse: (Response response) {
print("Avant de répondre");
// Do something with response data
return response; // continue
}, onError: (DioError e) {
print("Avant l'erreur");
// Do something with response error
return e; //continue
}));
Télécharger le fichier
/*
* Télécharger le fichier
*/
downloadFile(urlPath, savePath) async {
Response response;
try {
response = await dio.download(urlPath, savePath,onReceiveProgress: (int count, int total){
//Progrès
print("$count $total");
});
print('downloadFile success---------${response.data}');
} on DioError catch (e) {
print('downloadFile error---------$e');
formatError(e);
}
return response.data;
}
Demande d'annulation
/*
* Demande d'annulation
*
* Le mêmecancel token Peut être utilisé pour plusieurs demandes,Quand uncancel tokenQuand on annule,Toutes les utilisations de cecancel tokenToutes les demandes seront annulées..
* Donc les paramètres sont optionnels
*/
void cancelRequests(CancelToken token) {
token.cancel("cancelled");
}
HttpsVérification des certificats
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;
};
Exemple d'appel
var response = await HttpUtil().get("http://www.baidu.com");
print(response.toString());
Code complet
边栏推荐
- Obsidian基础教程
- 剖析虚幻渲染体系(16)- 图形驱动的秘密
- Simple record of fire & spell effects
- HotSpot JVM 「01」类加载、链接和初始化
- Win11 start menu right click blank? The right button of win11 start menu does not respond. Solution
- Exclusive interview with deepmindceo hassabis: we will see a new scientific Renaissance! AI's new achievements in nuclear fusion are officially announced today
- Free cloud function proxy IP pool just released
- Oracle case: does index range scan really not read multiple blocks?
- Summary of basic knowledge of neural network
- SOCKET编程部分I/O的初步解决
猜你喜欢
Oracle case: does index range scan really not read multiple blocks?

Win11 start menu right click blank? The right button of win11 start menu does not respond. Solution

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

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

Win11开始菜单右键空白?Win11开始菜单右键没反应解决方法

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

Various special effect cases of Experiment 3
![[HNU summer semester] preparation stage of database system design](/img/cf/5ff390e2662a8942fa22e2c41e0fb5.png)
[HNU summer semester] preparation stage of database system design

3.4 cloning and host time synchronization of VMware virtual machine

数据治理,说起来容易,做起来难
随机推荐
AbstractFactory Abstract Factory
[HNU summer semester] preparation stage of database system design
实验三的各种特效案例
Generic cmaf container for efficient cross format low latency delivery
Simple record of fire & spell effects
Sqlmap learning (sqli labs as an example)
Obsidian basic tutorial
SSH modifies grub in heiqunhui ds918+ system 7.0.1 cfg
JS disable the browser PDF printing and downloading functions (pdf.js disable the printing and downloading functions)
Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing Bing
Illustration de l'exécution du cadre de pile
用idea建立第一個網站
GridView component of swiftui 4 new features (tutorial includes source code)
【hnu暑学期】数据库系统设计 准备阶段
HNU network counting experiment: Experiment 4 application layer and transport layer protocol analysis (packettracer)
Dialog+: Audio dialogue enhancement technology based on deep learning
Audio orchestrator: orchestrate immersive interactive audio using multiple devices
Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
数字图像处理知识点总结概述
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