Dio是 http request的framework
也可以用内建的HttpClient或是http,
选择Dio则是觉得简单好用
还有interceptors拦截.
那废话不多说 直接上code
用singleton封装成自己要的class,
这边叫HttpUtil, server host统一写在 BASEURL这里,
可以在request前後,或发生例外状况时增加拦截,
这边碍於长度 就只列出get方法,其他的请参考下面附录的GitHub.
const BASEURL = "https://newsapi.org/v2";
class HttpUtil {
static final HttpUtil _instance = HttpUtil._internal();
late Dio dio;
factory HttpUtil() => _instance;
HttpUtil._internal() {
BaseOptions options = BaseOptions();
options.baseUrl = BASEURL;
options.receiveTimeout = 10000;
options.connectTimeout = 8000;
options.contentType = 'application/json';
dio = Dio(options);
// 添加拦截
dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
// Do something before request is sent
handler.next(options);
}, onResponse: (response, handler) {
// Do something with response data
return handler.next(response); // continue
}, onError: (DioError error, handler) async {
// Do something with response error
return handler.next(error);
}));
}
Future get(String path,
{dynamic params, Options? options, CancelToken? cancelToken}) async {
try {
setTokenToOptions();
var response = await dio.get(path,
queryParameters: params, cancelToken: cancelToken);
return response;
} on DioError catch (e) {
createErrorEntity(e);
return e;
}
}
}
本篇有参考自对岸猫哥的GitHub
下一篇继续位大家介绍Dio
(fetch News API, JOSN parsing, 与GetX结合)
<<: Day21-部署篇(三)Laravel 专案部署与 MySQL、Nginx 设定
>>: [ Day 21 ] 路由管理 - React Router 2/2
我在 Localhost 开发的时候会出现一个错误讯息困扰有许久,而且是机率性的。因为以 SPA(S...
上一篇我们已经完成心血管疾病资料的训练并且产生model档. 本篇我们再来加入MLflow的功能, ...
先建立一个hello的目录,编辑main.rs fn main() { print!("H...
今天要用昨天训练好的模型来试试看能否顺利从我们的目标网站取得资讯! 我们要先用selenium来处理...
本篇同步发布於个人Blog: [PoEAA] Data Source Architectural P...