You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.4 KiB
Dart

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_http2_adapter/dio_http2_adapter.dart';
import 'package:flutter/foundation.dart';
import 'package:isekai_wiki/global.dart';
import 'package:isekai_wiki/utils/api_utils.dart';
class HttpResponseCodeError extends Error {
int? statusCode;
HttpResponseCodeError(this.statusCode);
@override
String toString() {
return "Http error: $statusCode";
}
}
class BaseApi {
static Dio? _dioInstance;
static CookieJar? cookieJar;
static Dio createClient() {
var dio = Dio();
return dio;
}
static Dio getClient() {
_dioInstance ??= createClient();
if (!kIsWeb) {
// HTTP2
_dioInstance!.httpClientAdapter = Http2Adapter(
ConnectionManager(
idleTimeout: 10000,
),
);
// Cookie
cookieJar = PersistCookieJar();
_dioInstance!.interceptors.add(CookieManager(cookieJar!));
// 缓存
final cacheOptions = CacheOptions(
store: MemCacheStore(),
policy: CachePolicy.request,
maxStale: const Duration(days: 7),
priority: CachePriority.normal,
cipher: null,
keyBuilder: CacheOptions.defaultCacheKeyBuilder,
allowPostMethod: false,
);
_dioInstance!.interceptors
.add(DioCacheInterceptor(options: cacheOptions));
// 自定义Header
_dioInstance!.interceptors.add(
InterceptorsWrapper(onRequest: (options, handler) {
options.headers["X-IsekaiWikiApp-Version"] =
Global.packageInfo?.version ?? "unknow";
options.headers["User-Agent"] = "";
return handler.next(options);
}),
);
}
return _dioInstance!;
}
static Future<String> get(Uri uri, {Map<String, dynamic>? search}) async {
var res = await getClient().get<String>(
uri.toString(),
options: Options(responseType: ResponseType.plain),
);
if (res.statusCode != 200) {
throw HttpResponseCodeError(res.statusCode);
}
return res.data ?? "";
}
static Future<Map> getJson(Uri uri) async {
var resText = await get(uri);
var resData = jsonDecode(resText);
if (resData is Map) {
return resData;
} else {
return {};
}
}
}