当前位置:网站首页>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
边栏推荐
- TLog 助力盘古框架实现微服务链路日志追踪
- Processing of limit operator in Presto
- 熊市指南|一些本质的教训与具体的生存法则
- Créer le premier site Web avec idea
- Illustration de l'exécution du cadre de pile
- Q5 s905l firmware version 202109
- China bed and mattress market status research analysis and development prospect forecast report (2022)
- Touring band: a 5g based multi camera remote distributed video production experiment
- China coated abrasive tools industry market depth analysis and development strategy consulting report 2022-2028
- 智云健康上市在即:长期亏损,美年健康俞熔已退出,未来难言乐观
猜你喜欢

图解栈帧运行过程

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

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
In depth analysis of Flink fine-grained resource management

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

用idea建立第一个网站

js禁用浏览器 pdf 打印、下载功能(pdf.js 禁用打印下载、功能)

Huawei switch stack configuration

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

What if win11 cannot delete the folder? Win11 cannot delete folder
随机推荐
Analysis of gpl3.0 license software copyright dispute cases
Summary of basic knowledge of neural network
[WPF] XAML code skills that can be directly used for converting CAD engineering drawings to WPF
24 pictures to clarify TCP at one time
Créer le premier site Web avec idea
Fujilai pharmaceutical has passed the registration: the annual revenue is nearly 500million yuan. Xiangyun once illegally traded foreign exchange
A3.ansible production practice case -- system initialization roles
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
Opentelemetry architecture and terminology Introduction (Continued)
Win11开始菜单右键空白?Win11开始菜单右键没反应解决方法
Conglin environmental protection IPO meeting: annual profit of more than 200million to raise 2.03 billion
Market depth analysis and development strategy consulting report of China's fire equipment market 2022-2028
Jingwei Hengrun is registered through the science and Innovation Board: it plans to raise 5billion yuan, with a 9-month revenue of 2.1 billion yuan
ITU AI and multimedia Seminar: exploring new areas and cross SDO synergy
AbstractFactory Abstract Factory
Sqlmap learning (sqli labs as an example)
Obsidian basic tutorial
HNU network counting experiment: experiment I application protocol and packet analysis experiment (using Wireshark)
JS disable the browser PDF printing and downloading functions (pdf.js disable the printing and downloading functions)
MySQL Chapter 15 lock