feat(common): 新增基础设施 HAR(网络/鉴权/日志/状态/工具)

This commit is contained in:
AndyChen1024
2026-09-11 16:22:45 +08:00
parent 2dc02b44c7
commit b73e74fa4a
16 changed files with 307 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
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<string, string>): Promise<string> {
return this.request(url, http.RequestMethod.GET, undefined, header);
}
async post(url: string, body: string, header?: Record<string, string>): Promise<string> {
return this.request(url, http.RequestMethod.POST, body, header);
}
async put(url: string, body: string, header?: Record<string, string>): Promise<string> {
return this.request(url, http.RequestMethod.PUT, body, header);
}
async delete(url: string, header?: Record<string, string>): Promise<string> {
return this.request(url, http.RequestMethod.DELETE, undefined, header);
}
private async request(url: string, method: http.RequestMethod, body?: string,
header?: Record<string, string>): Promise<string> {
let headers: Record<string, string> = {};
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));
}
}
}