1. Dio
dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等...
1.1 Dio 引入
Dio 引入
dependencies:
dio: ^x.x.x #请使用pub上的最新版本
执行 flutter pub get命令,即可导入dio三方库
导入并创建dio实例:
import 'package:dio/dio.dart';
Dio dio = Dio();
注意,一个dio实例可以发起多个http请求,一般来说,APP只有一个http数据源时,dio应该使用单例模式。
1.2 基本使用
Get
final dio = Dio();
dio.get("https://httpbin.org/get").then((res) {
print(res);
});
final dio = Dio();
var res = await dio.get("https://httpbin.org/get");
print(res);
Post
final dio = Dio();
dio.post("https://httpbin.org/post").then((res) {
print(res);
});
final dio = Dio();
var res = await dio.post("https://httpbin.org/post");
print(res);
发起多个并发请求:
final dio = Dio();
var res = await Future.wait([
dio.post("https://httpbin.org/post"),
dio.get("https://httpbin.org/get")
]);
print(res);
下载文件
response=await dio.download("https://www.google.com/",_savePath);
发送 FormData:
FormData formData = FormData.from({
"name": "wendux",
"age": 25,
});
response = await dio.post("/info", data: formData)
如果发送的数据是FormData,则dio会将请求header的contentType设为“multipart/form-data”。
通过FormData上传多个文件:
var formData = FormData.fromMap({
'name': 'wendux',
'age': 25,
'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),
'files': [
await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt'),
await MultipartFile.fromFile('./text2.txt', filename: 'text2.txt'),
]
});
var response = await dio.post('/info', data: formData);
监听上传进度
response = await dio.post(
'http://www.dtworkroom.com/doris/1/2.0.0/test',
data: {'aa': 'bb' * 22},
onSendProgress: (int sent, int total) {
print('$sent $total');
},
);
设置代理、请求认证、证书校验
dio内部仍然使用HttpClient发起的请求,所以代理、请求认证、证书校验等和HttpClient是相同的,我们可以在onHttpClientCreate回调中设置,例如:
dio.httpClientAdapter = DefaultHttpClientAdapter();
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(client) {
// config the http client
client.findProxy = (uri) {
//proxy all request to localhost:8888
return 'PROXY localhost:8888';
};
client.badCertificateCallback =
(X509Certificate cert, String host, int port) {
if (cert.pem == "PEM") {
return true; //证书一致,则允许发送数据
}
return false;
};
};
注意: onHttpClientCreate会在当前dio实例内部需要创建HttpClient时调用,所以通过此回调配置HttpClient会对整个dio实例生效,如果你想针对某个应用请求单独的代理或证书校验策略,可以创建一个新的dio实例即可。
拦截器 InterceptorsWrapper
Interceptor dInter = InterceptorsWrapper(onRequest: (options, handler) {
print("拦截配置");
return handler.next(options);
}, onResponse: (res, handler) {
print("拦截数据");
return handler.next(res);
}, onError: (err, handler) {
print("拦截错误");
return handler.next(err);
});
自定义拦截器
class CustomInterceptors extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
print('REQUEST[${options.method}] => PATH: ${options.path}');
return super.onRequest(options, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
print(
'RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
return super.onResponse(response, handler);
}
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
print(
'ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
return super.onError(err, handler);
}
}
1.3 示例
import 'package:dio/dio.dart';
import 'config.dart';
class HttpRequest {
static final BaseOptions baseOptions = BaseOptions(
baseUrl: HttpConfig.baseURL, connectTimeout: HttpConfig.timeout);
static final Dio dio = Dio(baseOptions);
static Future<T> request<T>(String url,
{String method = "get",
Map<String, dynamic>? params,
Interceptor? inter}) async {
// 1.创建单独配置
final Options specialOptions = Options(method: method);
// 拦截器
Interceptor dInter = InterceptorsWrapper(onRequest: (options, handler) {
print("拦截配置");
return handler.next(options);
}, onResponse: (res, handler) {
print("拦截数据");
return handler.next(res);
}, onError: (err, handler) {
print("拦截错误");
return handler.next(err);
});
// 自定义Interceptor
CustomInterceptors cInter = CustomInterceptors();
List<Interceptor> inters = [cInter];
if (inter != null) {
inters.add(inter);
}
dio.interceptors.addAll(inters);
// 发送网络请求
try {
Response resp = await dio.request(url,
queryParameters: params, options: specialOptions);
return resp.data;
} on DioError catch (e) {
return Future.error(e);
}
}
}
class CustomInterceptors extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
print('REQUEST[${options.method}] => PATH: ${options.path}');
return super.onRequest(options, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
print(
'RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
return super.onResponse(response, handler);
}
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
print(
'ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
return super.onError(err, handler);
}
}
class HttpConfig {
static const String baseURL = "https://httpbin.org/";
static const int timeout = 5000;
}