这是CaiYouHui前端,一个关于flutter的安卓app,前端使用flutter实现

api_client.dart 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import 'dart:convert';
  2. import 'package:http/http.dart' as http;
  3. import 'package:shared_preferences/shared_preferences.dart';
  4. import './secure_http_client.dart';
  5. class ApiClient {
  6. final http.Client _httpClient;
  7. final SharedPreferences _prefs;
  8. ApiClient(this._prefs) : _httpClient = SecureHttpClient.createSecureClient();
  9. // 获取认证头
  10. Map<String, String> _getHeaders({bool withAuth = true}) {
  11. final headers = {
  12. 'Content-Type': 'application/json',
  13. 'Accept': 'application/json',
  14. };
  15. if (withAuth) {
  16. final token = _prefs.getString('access_token');
  17. if (token != null && token.isNotEmpty) {
  18. headers['Authorization'] = 'Bearer $token';
  19. }
  20. }
  21. return headers;
  22. }
  23. // 通用POST请求
  24. Future<http.Response> post(
  25. String url,
  26. Map<String, dynamic> body,
  27. {bool withAuth = false}
  28. ) async {
  29. try {
  30. final response = await _httpClient.post(
  31. Uri.parse(url),
  32. headers: _getHeaders(withAuth: withAuth),
  33. body: json.encode(body),
  34. );
  35. return response;
  36. } catch (e) {
  37. throw Exception('网络请求失败: $e');
  38. }
  39. }
  40. // 通用GET请求
  41. Future<http.Response> get(
  42. String url,
  43. {bool withAuth = true}
  44. ) async {
  45. try {
  46. final response = await _httpClient.get(
  47. Uri.parse(url),
  48. headers: _getHeaders(withAuth: withAuth),
  49. );
  50. return response;
  51. } catch (e) {
  52. throw Exception('网络请求失败: $e');
  53. }
  54. }
  55. // 通用PUT请求
  56. Future<http.Response> put(
  57. String url,
  58. Map<String, dynamic> body,
  59. {bool withAuth = true}
  60. ) async {
  61. try {
  62. final response = await _httpClient.put(
  63. Uri.parse(url),
  64. headers: _getHeaders(withAuth: withAuth),
  65. body: json.encode(body),
  66. );
  67. return response;
  68. } catch (e) {
  69. throw Exception('网络请求失败: $e');
  70. }
  71. }
  72. // 保存tokens
  73. Future<void> saveTokens(String accessToken, String? refreshToken) async {
  74. await _prefs.setString('access_token', accessToken);
  75. if (refreshToken != null && refreshToken.isNotEmpty) {
  76. await _prefs.setString('refresh_token', refreshToken);
  77. }
  78. }
  79. // 清除所有token
  80. Future<void> clearTokens() async {
  81. await _prefs.remove('access_token');
  82. await _prefs.remove('refresh_token');
  83. }
  84. // 获取refresh_token
  85. String? getRefreshToken() {
  86. return _prefs.getString('refresh_token');
  87. }
  88. // 检查是否已登录
  89. bool isLoggedIn() {
  90. final token = _prefs.getString('access_token');
  91. return token != null && token.isNotEmpty;
  92. }
  93. }