引入依赖
Dio地址:https://pub.dev/packages/dio
dependencies:
dio: ^4.0.6
进行封装
封装一个全局的Dio
import 'package:dio/dio.dart';
class HttpGlobal{
static Dio? _dio;
static Dio httpClient(){
if(_dio == null){
_dio = new Dio();
_dio?.options = new BaseOptions(
//配置接口地址
baseUrl: "https://www.jianshu.com",
//配置连接超时时间
connectTimeout: 5000,
//配置发送超时时间
sendTimeout: 5000,
//配置接收超时时间
receiveTimeout: 5000,
//配置请求头
headers: {
},
//配置contentType
contentType: Headers.jsonContentType,
//配置responseType
responseType: ResponseType.json,
);
//请求的拦截
_dio?.interceptors.add(new InterceptorsWrapper(
onRequest:(options,handler){
print("请求" + options.extra.toString());
handler.next(options);
},
onError: (e,handler){
print("请求出错");
handler.next(e);
},
onResponse: (response,handler){
print("请求返回");
handler.next(response);
}
));
}
return _dio!;
}
}
使用
void test()async{
var result = await HttpGlobal.httpClient().get("/");
print(result);
}
更多的请求方式可以在官方页面查看:https://pub.dev/packages/dio
网友评论