XuqmGroup-HarmonySDK/xuqm-sdk/src/main/ets/core/HttpClient.ets

57 行
1.7 KiB
Plaintext

2026-04-21 22:07:29 +08:00
import http from '@ohos.net.http'
import type { ApiResponse, HttpHeaders } from './Types'
2026-04-21 22:07:29 +08:00
import { SDKContext } from './SDKContext'
export class HttpClient {
static async request<T>(
method: http.RequestMethod,
path: string,
body?: Object,
query?: string,
): Promise<T> {
2026-04-21 22:07:29 +08:00
const config = SDKContext.getConfig()
const token = SDKContext.getToken()
const url = config.apiBaseUrl.replace(/\/$/, '') + path + (query ? '?' + query : '')
2026-04-21 22:07:29 +08:00
const client = http.createHttp()
try {
const header: HttpHeaders = {
'Content-Type': 'application/json',
}
if (token) {
header.Authorization = 'Bearer ' + token
}
2026-04-21 22:07:29 +08:00
const options: http.HttpRequestOptions = {
method,
header,
extraData: body ? JSON.stringify(body) : '',
2026-04-21 22:07:29 +08:00
connectTimeout: 15000,
readTimeout: 15000,
}
const res = await client.request(url, options)
const json: ApiResponse<T> = JSON.parse(res.result as string) as ApiResponse<T>
if (json.code !== 200) throw new Error(json.message)
return json.data
} finally {
client.destroy()
}
}
static get<T>(path: string, query?: string): Promise<T> {
return HttpClient.request<T>(http.RequestMethod.GET, path, undefined, query)
2026-04-21 22:07:29 +08:00
}
static post<T>(path: string, body?: Object, query?: string): Promise<T> {
return HttpClient.request<T>(http.RequestMethod.POST, path, body, query)
2026-04-21 22:07:29 +08:00
}
static put<T>(path: string, body?: Object, query?: string): Promise<T> {
return HttpClient.request<T>(http.RequestMethod.PUT, path, body, query)
2026-04-21 22:07:29 +08:00
}
static delete<T>(path: string, query?: string): Promise<T> {
return HttpClient.request<T>(http.RequestMethod.DELETE, path, undefined, query)
2026-04-21 22:07:29 +08:00
}
}