HarmonyOSBaseLibs/src/main/ets/http/HttpHelperX.ts

73 行
1.7 KiB
TypeScript

import { ToolsHelperForTS } from '../utils/ToolsHelperForTS';
export interface HttpParamsGet {
url: string
query?: Record<string, string> | Object
headers?: Record<string, string | null | undefined>
}
export interface HttpParamsPost {
url: string
data?: string | Object | ArrayBuffer
query?: Record<string, string> | Object
headers?: Record<string, string | null | undefined>
}
export interface HttpParamsForm {
url: string
data?: Record<string, string> | Object | undefined
query?: Record<string, string> | Object
headers?: Record<string, string | null | undefined>
}
export class HttpHelperX {
/**
*
* @param ct Content-Type
* @param headers
* @returns
*/
static getHeaders(ct: string, headers?: Record<string, string>) {
return {
"Content-Type": ct,
// "Accept": "application/json",
...headers
}
}
static getUrl(url: string, query?: Record<string, string> | Object) {
let u = url
if (query) {
let q = query
if (typeof query === 'object') {
q = ToolsHelperForTS.classToRecord(query)
}
u = `${u}${u.indexOf('?') < 0 ? '?' : u.endsWith('$') ? '' : '&'}`
Object.entries(q).forEach((row) => {
if (row[1]) {
u = `${u}${row[0]}=${row[1] as string}&`
}
});
u = u.slice(0, u.length - 1)
}
return u
}
static getContent(data?: Record<string, string> | Object) {
if (!data) {
return undefined
}
let u = ''
let q = data
if (typeof data === 'object') {
q = ToolsHelperForTS.classToRecord(data)
}
Object.entries(q).forEach((row) => {
if (row[1]) {
u = `${u}${row[0]}=${row[1] as string}&`
}
});
u = u.slice(0, u.length - 1)
return u
}
}