2026-04-21 22:07:29 +08:00
|
|
|
import http from '@ohos.net.http'
|
2026-04-28 20:11:37 +08:00
|
|
|
import type { ApiResponse, HttpHeaders } from './Types'
|
2026-04-21 22:07:29 +08:00
|
|
|
import { SDKContext } from './SDKContext'
|
|
|
|
|
|
|
|
|
|
export class HttpClient {
|
2026-04-28 16:55:11 +08:00
|
|
|
static async request<T>(
|
|
|
|
|
method: http.RequestMethod,
|
|
|
|
|
path: string,
|
2026-04-28 20:11:37 +08:00
|
|
|
body?: Object,
|
|
|
|
|
query?: string,
|
2026-04-28 16:55:11 +08:00
|
|
|
): Promise<T> {
|
2026-04-21 22:07:29 +08:00
|
|
|
const config = SDKContext.getConfig()
|
|
|
|
|
const token = SDKContext.getToken()
|
2026-04-28 20:11:37 +08:00
|
|
|
const url = config.apiBaseUrl.replace(/\/$/, '') + path + (query ? '?' + query : '')
|
2026-04-21 22:07:29 +08:00
|
|
|
|
|
|
|
|
const client = http.createHttp()
|
|
|
|
|
try {
|
2026-04-28 20:11:37 +08:00
|
|
|
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,
|
2026-04-28 20:11:37 +08:00
|
|
|
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()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-28 20:11:37 +08:00
|
|
|
static get<T>(path: string, query?: string): Promise<T> {
|
2026-04-28 16:55:11 +08:00
|
|
|
return HttpClient.request<T>(http.RequestMethod.GET, path, undefined, query)
|
2026-04-21 22:07:29 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-28 20:11:37 +08:00
|
|
|
static post<T>(path: string, body?: Object, query?: string): Promise<T> {
|
2026-04-28 16:55:11 +08:00
|
|
|
return HttpClient.request<T>(http.RequestMethod.POST, path, body, query)
|
2026-04-21 22:07:29 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-28 20:11:37 +08:00
|
|
|
static put<T>(path: string, body?: Object, query?: string): Promise<T> {
|
2026-04-28 16:55:11 +08:00
|
|
|
return HttpClient.request<T>(http.RequestMethod.PUT, path, body, query)
|
2026-04-21 22:07:29 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-28 20:11:37 +08:00
|
|
|
static delete<T>(path: string, query?: string): Promise<T> {
|
2026-04-28 16:55:11 +08:00
|
|
|
return HttpClient.request<T>(http.RequestMethod.DELETE, path, undefined, query)
|
2026-04-21 22:07:29 +08:00
|
|
|
}
|
|
|
|
|
}
|