Files
harmony-client/common/src/main/ets/network/HttpClient.ets

66 lines
2.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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));
}
}
}