Flutter教程——Dio的封装
程序员文章站
2024-02-28 11:45:10
...
Dio是开源的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等…
一,首先,添加依赖 https://github.com/flutterchina/dio 可以看这儿的版本,在pubspec.yaml文件下添加:
要注意对齐,否则报错“pubspec.yaml: A dependency may only have one source.”
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
# 注意,这儿有个大坑,dio必须在dependencies下一级,别加空格或tab,否则加不进来
dio: ^3.0.9
二,看下最简单的用法
Dio dio = new Dio();
//get请求
void getHttp() async {
try{
Response response = await dio.get("http://www.baidu.com");
print("getHttp: $response");
}catch(e){
print("getHttp: Exception: $e");
}
}
//post请求
void postHttp() async {
try{
Response response = await dio.post("https://www.csdn.net");
print("postHttp: $response");
}catch(e){
print("postHttp: Exception: $e");
}
}
三,封装
因为一个dio实例可以发起多个http请求,所以最好使用单例模式,节省资源;
直接贴代码:
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';
class HttpManager{
//一个人工智能回答的免费API
final String _BASEURL = 'http://api.qingyunke.com/api.php';
final int _CONNECTTIMEOUT = 5000;
final int _RECEIVETIMEOUT = 3000;
//单例模式
static HttpManager _instance;
Dio _dio;
BaseOptions _options;
//单例模式,只创建一次实例
static HttpManager getInstance(){
if(null == _instance){
_instance = new HttpManager();
return _instance;
}
}
//构造函数
HttpManager(){
_options =new BaseOptions(
baseUrl: _BASEURL,
//连接时间为5秒
connectTimeout: _CONNECTTIMEOUT,
//响应时间为3秒
receiveTimeout: _RECEIVETIMEOUT,
//设置请求头
headers: {
"resource":"android"
},
//默认值是"application/json; charset=utf-8",Headers.formUrlEncodedContentType会自动编码请求体.
contentType: Headers.formUrlEncodedContentType,
//共有三种方式json,bytes(响应字节),stream(响应流),plain
responseType: ResponseType.json
);
_dio = new Dio(_options);
//设置Cookie
_dio.interceptors.add(CookieManager(CookieJar()));
//添加拦截器
_dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options){
print("在请求之前的拦截信息");
return options;
},
onResponse: (Response response){
print("在响应之前的拦截信息");
return response;
},
onError: (DioError e){
print("在错误之前的拦截信息");
return e;
}
));
}
//get请求方法
get(url,{data,options,cancelToken}) async{
Response response;
try{
response = await _dio.get(url,queryParameters: data,options: options,cancelToken: cancelToken);
print('getHttp response: $response');
}on DioError catch(e){
print('getHttp exception: $e');
formatError(e);
}
return response;
}
//post请求
post(url,{params,options,cancelToken}) async{
Response response;
try{
response = await _dio.post(url,queryParameters: params,options: options,cancelToken: cancelToken);
print('postHttp response: $response');
}on DioError catch(e){
print('postHttp exception: $e');
formatError(e);
}
return response;
}
//post Form请求
postForm(url,{data,options,cancelToken}) async{
Response response;
try{
response = await _dio.post(url,options: options,cancelToken: cancelToken,data: data);
print('postHttp response: $response');
}on DioError catch(e){
print('postHttp exception: $e');
formatError(e);
}
return response;
}
//下载文件
downLoadFile(urlPath,savePath) async{
Response response;
try{
response = await _dio.download(urlPath, savePath,onReceiveProgress: (int count,int total){
print('$count $total');
});
print('downLoadFile response: $response');
}on DioError catch(e){
print('downLoadFile exception: $e');
formatError(e);
}
return response;
}
//取消请求
cancleRequests(CancelToken token){
token.cancel("cancelled");
}
void formatError(DioError e) {
if (e.type == DioErrorType.CONNECT_TIMEOUT) {
print("连接超时");
} else if (e.type == DioErrorType.SEND_TIMEOUT) {
print("请求超时");
} else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
print("响应超时");
} else if (e.type == DioErrorType.RESPONSE) {
print("出现异常");
} else if (e.type == DioErrorType.CANCEL) {
print("请求取消");
} else {
print("未知错误");
}
}
}
调用时只需:
http.HttpManager.getInstance().get('',params:{'key': 'free','msg': '鹅鹅鹅'});
输出:
2020-04-17 14:42:30.252 25364-25460/com.example.flutter_module.host I/flutter: 在请求之前的拦截信息
2020-04-17 14:42:31.145 25364-25460/com.example.flutter_module.host I/flutter: 在响应之前的拦截信息
2020-04-17 14:42:31.148 25364-25460/com.example.flutter_module.host I/flutter: getHttp response: {"result":0,"content":"曲项向天歌"}
其实我觉得响应结果转为json就很好用了,如果喜欢转为实体类,自己再稍加封装就好。
下一篇: Yii2框架数据库简单的增删改查语法小结