import { http } from '@kit.NetworkKit'; import { HttpInterceptor } from './HttpInterceptor'; import { ApiError } from './ApiError'; /** * HTTP 客户端封装:统一超时、请求头、拦截器链。 * 基于 @kit.NetworkKit 的 http 模块(Promise 风格)。 */ export class HttpClient { private readonly client: http.HttpRequest = http.createHttp(); private interceptors: HttpInterceptor[] = []; addInterceptor(interceptor: HttpInterceptor): HttpClient { this.interceptors.push(interceptor); return this; } async get(url: string, header?: Record): Promise { return this.request(url, http.RequestMethod.GET, undefined, header); } async post(url: string, body: string, header?: Record): Promise { return this.request(url, http.RequestMethod.POST, body, header); } async put(url: string, body: string, header?: Record): Promise { return this.request(url, http.RequestMethod.PUT, body, header); } async delete(url: string, header?: Record): Promise { return this.request(url, http.RequestMethod.DELETE, undefined, header); } private async request(url: string, method: http.RequestMethod, body?: string, header?: Record): Promise { let headers: Record = {}; if (header !== undefined) { headers = header; } for (const interceptor of this.interceptors) { headers = interceptor.onRequest(headers); } const options: http.HttpRequestOptions = { method: method, header: headers, expectDataType: http.HttpDataType.STRING, connectTimeout: 10000, readTimeout: 10000 }; if (body !== undefined) { options.extraData = body; } try { const response: http.HttpResponse = await this.client.request(url, options); for (const interceptor of this.interceptors) { interceptor.onResponse(response.responseCode, response.result as string); } return response.result as string; } catch (err) { throw ApiError.network(JSON.stringify(err)); } } }