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.
52 lines
1.1 KiB
Dart
52 lines
1.1 KiB
Dart
2 years ago
|
import 'dart:convert';
|
||
|
|
||
|
import 'package:flutter/foundation.dart';
|
||
|
import 'package:isekai_wiki/global.dart';
|
||
|
import 'package:isekai_wiki/utils/api_utils.dart';
|
||
|
import 'package:http/http.dart' as http;
|
||
|
|
||
|
class HttpResponseCodeError extends Error {
|
||
|
int? statusCode;
|
||
|
|
||
|
HttpResponseCodeError(this.statusCode);
|
||
|
|
||
|
@override
|
||
|
String toString() {
|
||
|
return "Http error: $statusCode";
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class BaseApi {
|
||
|
static Future<Map<String, String>> _getHeaders() async {
|
||
|
Map<String, String> headers = {};
|
||
|
|
||
|
if (!kIsWeb) {
|
||
|
headers["X-IsekaiWikiApp-Version"] = Global.packageInfo?.version ?? "unknow";
|
||
|
headers["User-Agent"] = await ApiUtils.getUserAgent();
|
||
|
}
|
||
|
|
||
|
return headers;
|
||
|
}
|
||
|
|
||
|
static Future<String> get(Uri uri, {Map<String, dynamic>? search}) async {
|
||
|
var res = await http.get(uri, headers: await _getHeaders());
|
||
|
|
||
|
if (res.statusCode != 200) {
|
||
|
throw HttpResponseCodeError(res.statusCode);
|
||
|
}
|
||
|
|
||
|
return res.body;
|
||
|
}
|
||
|
|
||
|
static Future<Map> getJson(Uri uri) async {
|
||
|
var resText = await get(uri);
|
||
|
var resData = jsonDecode(resText);
|
||
|
|
||
|
if (resData is Map) {
|
||
|
return resData;
|
||
|
} else {
|
||
|
return {};
|
||
|
}
|
||
|
}
|
||
|
}
|