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結合)