/// 基于 `dio` 的 API 客户端:拦截器、`CancelToken`、`FormData`。 /// /// 为什么还讲 dio?`http` 够简单,但真实项目迟早需要: /// - 统一拦截(鉴权头、日志脱敏、错误映射、重试) /// - 取消请求(用户离开页面时取消,省流量也省服务器) /// - 上传进度 / 下载进度 / 请求去重 /// dio 把这些都做成了内置能力。 library; import 'dart:async'; import 'package:dio/dio.dart'; import 'api_exception.dart'; import 'post.dart'; class DioPostsApi { DioPostsApi({Dio? dio, this.baseUrl = 'https://jsonplaceholder.typicode.com'}) : dio = dio ?? Dio( BaseOptions( baseUrl: baseUrl, connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10), headers: {'Accept': 'application/json'}, responseType: ResponseType.json, ), ) { this.dio.interceptors.add( InterceptorsWrapper( onRequest: (RequestOptions options, RequestInterceptorHandler handler) { // 鉴权头统一注入:业务代码不用每个请求都写。 options.headers['Authorization'] = 'Bearer '; handler.next(options); }, onResponse: (Response response, ResponseInterceptorHandler handler) { handler.next(response); }, onError: (DioException error, ErrorInterceptorHandler handler) { // 这里只做"记录/上报"。真正的类型映射放在 _asApiException: // 在拦截器里再包一层 DioException 容易出现"漏掉 response/statusCode"的问题。 handler.next(error); }, ), ); } final Dio dio; final String baseUrl; /// [cancelToken] 让调用方可以取消请求(离开页面时调用 `cancel()`)。 Future> fetchPosts({int limit = 20, CancelToken? cancelToken}) async { try { final Response> response = await dio.get>( '/posts', queryParameters: {'_limit': limit}, cancelToken: cancelToken, ); final List data = response.data ?? const []; return [ for (final Object? raw in data) if (raw is Map) Post.fromJson(raw), ]; } on DioException catch (e) { throw _asApiException(e); } } /// POST JSON。 Future createPost({ required String title, required String body, CancelToken? cancelToken, }) async { try { final Response> response = await dio.post>( '/posts', data: {'title': title, 'body': body, 'userId': 1}, cancelToken: cancelToken, ); return (response.data?['id'] as num?)?.toInt() ?? 0; } on DioException catch (e) { throw _asApiException(e); } } /// FormData:文件上传(真正发请求时是 multipart/form-data)。 Future uploadBytes({ required List bytes, required String filename, void Function(int sent, int total)? onSendProgress, CancelToken? cancelToken, }) async { final FormData form = FormData.fromMap({ 'file': MultipartFile.fromBytes(bytes, filename: filename), 'note': 'uploaded from ch13 demo', }); try { await dio.post( '/upload', data: form, onSendProgress: onSendProgress, cancelToken: cancelToken, ); } on DioException catch (e) { throw _asApiException(e); } } static ApiException _asApiException(DioException e) { if (e.error is ApiException) return e.error! as ApiException; switch (e.type) { case DioExceptionType.cancel: return const RequestCancelledException(); case DioExceptionType.connectionTimeout: case DioExceptionType.sendTimeout: case DioExceptionType.receiveTimeout: return ApiTimeoutException('请求超时', cause: e); case DioExceptionType.connectionError: case DioExceptionType.unknown: return NetworkException(e.message ?? '网络错误', cause: e); case DioExceptionType.badResponse: final int? code = e.response?.statusCode; if (code == null) return NetworkException('响应异常', cause: e); return HttpStatusException(code, e.response?.data.toString() ?? ''); case DioExceptionType.badCertificate: return NetworkException('证书校验失败', cause: e); case DioExceptionType.transformTimeout: return const ApiTimeoutException('响应解析超时'); } } }