| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import 'dart:convert';
- import 'package:http/http.dart' as http;
- import 'package:shared_preferences/shared_preferences.dart';
- import './secure_http_client.dart';
-
- class ApiClient {
- final http.Client _httpClient;
- final SharedPreferences _prefs;
-
- ApiClient(this._prefs) : _httpClient = SecureHttpClient.createSecureClient();
-
- // 获取认证头
- Map<String, String> _getHeaders({bool withAuth = true}) {
- final headers = {
- 'Content-Type': 'application/json',
- 'Accept': 'application/json',
- };
-
- if (withAuth) {
- final token = _prefs.getString('access_token');
- if (token != null && token.isNotEmpty) {
- headers['Authorization'] = 'Bearer $token';
- }
- }
-
- return headers;
- }
-
- // 通用POST请求
- Future<http.Response> post(
- String url,
- Map<String, dynamic> body,
- {bool withAuth = false}
- ) async {
- try {
- final response = await _httpClient.post(
- Uri.parse(url),
- headers: _getHeaders(withAuth: withAuth),
- body: json.encode(body),
- );
- return response;
- } catch (e) {
- throw Exception('网络请求失败: $e');
- }
- }
-
- // 通用GET请求
- Future<http.Response> get(
- String url,
- {bool withAuth = true}
- ) async {
- try {
- final response = await _httpClient.get(
- Uri.parse(url),
- headers: _getHeaders(withAuth: withAuth),
- );
- return response;
- } catch (e) {
- throw Exception('网络请求失败: $e');
- }
- }
-
- // 通用PUT请求
- Future<http.Response> put(
- String url,
- Map<String, dynamic> body,
- {bool withAuth = true}
- ) async {
- try {
- final response = await _httpClient.put(
- Uri.parse(url),
- headers: _getHeaders(withAuth: withAuth),
- body: json.encode(body),
- );
- return response;
- } catch (e) {
- throw Exception('网络请求失败: $e');
- }
- }
-
- // 保存token
- Future<void> saveToken(String token) async {
- await _prefs.setString('access_token', token);
- }
-
- // 清除token
- Future<void> clearToken() async {
- await _prefs.remove('access_token');
- }
-
- // 检查是否已登录
- bool isLoggedIn() {
- final token = _prefs.getString('access_token');
- return token != null && token.isNotEmpty;
- }
- }
|