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

347 行
14 KiB
TypeScript

2024-05-07 17:41:21 +08:00
import { ArrayList, HashMap } from '@kit.ArkTS';
import http from '@ohos.net.http';
2024-10-20 17:59:30 +08:00
import { SZYXLocalStorageHelper } from '../utils/SZYXLocalStorageHelper';
import { SZYXLocalStorageKeys } from '../utils/SZYXLocalStorageKeys';
2024-10-22 16:10:15 +08:00
import { ToolsHelperForTS } from '../utils/ToolsHelperForTS';
2024-05-07 17:41:21 +08:00
2024-10-10 19:22:29 +08:00
type HttpParamsGet = {
2024-05-08 16:20:49 +08:00
url: string
2024-10-10 19:22:29 +08:00
query?: Record<string, string> | Object
headers?: Record<string, string>
}
type HttpParamsPost = {
url: string
2024-10-19 15:12:22 +08:00
data?: string | Object | ArrayBuffer
2024-10-10 19:22:29 +08:00
query?: Record<string, string> | Object
headers?: Record<string, string>
}
type HttpParamsForm = {
url: string
2024-10-21 19:54:10 +08:00
data?: Record<string, string> | Object|undefined
2024-05-08 16:20:49 +08:00
query?: Record<string, string> | Object
headers?: Record<string, string>
}
2024-05-07 17:41:21 +08:00
export class HttpHelper {
private static instance: HttpHelper | null = null
// 单例模式
static get() {
// 判断系统是否已经有单例了
if (HttpHelper.instance === null) {
HttpHelper.instance = new HttpHelper()
}
return HttpHelper.instance
}
//请求中队列
private httpHandlerList = new HashMap<string, http.HttpRequest>();
// 并发白名单,这个名单里面的api,重复请求不会取消
private concurrentList = new ArrayList<string>();
constructor() {
this.httpHandlerList = new HashMap<string, http.HttpRequest>();
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
this.concurrentList.clear()
}
/**
*
* @param apiNo
*/
public addConcurrent(apiNo: string) {
if (this.concurrentList.getIndexOf(apiNo) === -1) {
this.concurrentList.add(apiNo)
}
}
public removeConcurrent(apiNo: string) {
if (this.concurrentList.getIndexOf(apiNo) !== -1) {
this.concurrentList.remove(apiNo)
}
}
/**
* postJson请求
* @param url url地址
* @param headers
* @param apiNo 使|使
* @returns
*/
2024-10-10 19:22:29 +08:00
public postJson<T>(params: HttpParamsPost, apiNo?: string): Promise<T> {
2024-05-07 17:41:21 +08:00
return new Promise<T>((resolve, reject) => {
2024-10-18 20:30:27 +08:00
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
this.httpHandlerList.hasKey(apiNo ?? params.url)) {
2024-05-08 16:20:49 +08:00
this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
let httpRequest = http.createHttp();
2024-05-08 16:20:49 +08:00
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
const header = {
2024-05-08 16:20:49 +08:00
"Content-Type": "application/json;charset=UTF-8",
// "Accept": "application/json",
...params.headers
2024-05-07 17:41:21 +08:00
}
2024-10-10 19:22:29 +08:00
console.log('=====>', 'POST:', JSON.stringify(params))
// console.log('=====>', '接口请求', JSON.stringify(header))
// console.log('=====>', '接口请求', data)
2024-05-07 17:41:21 +08:00
2024-05-08 16:20:49 +08:00
httpRequest.request(this.getUrl(params.url, params.query), {
2024-05-07 17:41:21 +08:00
method: http.RequestMethod.POST,
2024-05-08 16:20:49 +08:00
connectTimeout: 20000,
readTimeout: 20000,
2024-05-07 17:41:21 +08:00
header: header,
2024-05-08 16:20:49 +08:00
extraData: params.data
2024-05-07 17:41:21 +08:00
})
.then((data: http.HttpResponse) => {
2024-10-18 20:30:27 +08:00
console.info(`=====>Result:${data.result as string}(${apiNo})`);
2024-05-08 16:54:06 +08:00
// console.info('=====>' + 'code:' + data.responseCode);
2024-05-07 17:41:21 +08:00
// console.info('=====>' + 'type:' + JSON.stringify(data.resultType));
// console.info('=====>' + 'header:' + JSON.stringify(data.header));
// console.info('=====>' + 'cookies:' + data.cookies); // 自API version 8开始支持cookie
// console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
// console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
2024-05-08 16:20:49 +08:00
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
if (data.responseCode === 200) {
2024-05-08 16:20:49 +08:00
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
2024-05-07 17:41:21 +08:00
} else {
2024-10-15 17:39:02 +08:00
const err: Error = new Error()
err.name = data.responseCode.toString()
err.message = '服务异常'
reject(err)
2024-05-07 17:41:21 +08:00
}
}).catch((err: Error) => {
2024-10-18 20:30:27 +08:00
console.info('=====>' + 'Error:' + JSON.stringify({ err: err, url: params.url, }));
2024-05-08 16:20:49 +08:00
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
2024-10-18 20:30:27 +08:00
} else {
2024-05-07 17:41:21 +08:00
reject(err)
2024-10-18 20:30:27 +08:00
}
2024-05-07 17:41:21 +08:00
});
});
}
2024-10-10 19:22:29 +08:00
/**
* postForm请求
* @param url url地址
* @param headers
* @param apiNo 使|使
* @returns
*/
public postForm<T>(params: HttpParamsForm, apiNo?: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
2024-10-18 20:30:27 +08:00
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
this.httpHandlerList.hasKey(apiNo ?? params.url)) {
2024-10-10 19:22:29 +08:00
this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-10-10 19:22:29 +08:00
}
let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-10-10 19:22:29 +08:00
}
const header = {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
// "Accept": "application/json",
...params.headers
}
let data = this.getContent(params.data)
2024-10-11 17:56:56 +08:00
2024-10-10 19:22:29 +08:00
console.log('=====>', 'POSTForm:', params.url)
console.log('=====>', 'POSTForm:', JSON.stringify(header))
console.log('=====>', 'POSTForm:', data)
httpRequest.request(this.getUrl(params.url, params.query), {
method: http.RequestMethod.POST,
connectTimeout: 20000,
readTimeout: 20000,
header: header,
2024-10-21 19:54:10 +08:00
extraData: data?encodeURI(data):undefined
2024-10-10 19:22:29 +08:00
})
.then((data: http.HttpResponse) => {
2024-10-18 20:30:27 +08:00
console.info(`=====>Result:${data.result as string}(${apiNo})`);
2024-10-10 19:22:29 +08:00
// console.info('=====>' + 'code:' + data.responseCode);
// console.info('=====>' + 'type:' + JSON.stringify(data.resultType));
// console.info('=====>' + 'header:' + JSON.stringify(data.header));
// console.info('=====>' + 'cookies:' + data.cookies); // 自API version 8开始支持cookie
// console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
// console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-10-10 19:22:29 +08:00
}
if (data.responseCode === 200) {
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
} else {
2024-10-15 17:39:02 +08:00
const err: Error = new Error()
err.name = data.responseCode.toString()
err.message = '服务异常'
reject(err)
2024-10-10 19:22:29 +08:00
}
}).catch((err: Error) => {
2024-10-18 20:30:27 +08:00
console.info('=====>' + 'Error:' + JSON.stringify({ err: err, url: params.url, }));
2024-10-10 19:22:29 +08:00
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-10-10 19:22:29 +08:00
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
2024-10-18 20:30:27 +08:00
} else {
2024-10-10 19:22:29 +08:00
reject(err)
2024-10-18 20:30:27 +08:00
}
2024-10-10 19:22:29 +08:00
});
});
}
2024-05-08 16:20:49 +08:00
2024-05-07 17:41:21 +08:00
/**
* get请求
* @param url url地址
* @param data
* @param headers
* @param apiNo 使|使
* @returns
*/
2024-10-10 19:22:29 +08:00
public get<T>(params: HttpParamsGet, apiNo?: string): Promise<T> {
2024-05-07 17:41:21 +08:00
return new Promise<T>((resolve, reject) => {
2024-10-18 20:30:27 +08:00
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
this.httpHandlerList.hasKey(apiNo ?? params.url)) {
2024-05-08 16:20:49 +08:00
this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
let httpRequest = http.createHttp();
2024-05-08 16:20:49 +08:00
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
const header = {
2024-05-08 16:20:49 +08:00
...params.headers
2024-05-07 17:41:21 +08:00
}
2024-10-10 19:22:29 +08:00
console.log('=====>', 'GET:', this.getUrl(params.url, params.query))
2024-10-15 15:58:40 +08:00
console.log('=====>', 'header:', JSON.stringify(header))
2024-05-07 17:41:21 +08:00
2024-05-08 16:20:49 +08:00
httpRequest.request(this.getUrl(params.url, params.query), {
2024-05-07 17:41:21 +08:00
method: http.RequestMethod.GET,
2024-05-08 16:20:49 +08:00
connectTimeout: 20000,
readTimeout: 20000,
2024-05-07 17:41:21 +08:00
header: header,
2024-10-10 19:22:29 +08:00
// extraData: params.data
2024-05-07 17:41:21 +08:00
})
.then((data: http.HttpResponse) => {
2024-10-18 20:30:27 +08:00
console.info(`=====>Result:${data.result as string}(${apiNo})`);
2024-05-08 15:14:24 +08:00
// console.info('=====>' + 'code:' + data.responseCode);
2024-05-07 17:41:21 +08:00
// console.info('=====>' + 'type:' + JSON.stringify(data.resultType));
// console.info('=====>' + 'header:' + JSON.stringify(data.header));
// console.info('=====>' + 'cookies:' + data.cookies); // 自API version 8开始支持cookie
// console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
// console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
2024-05-08 16:20:49 +08:00
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
if (data.responseCode === 200) {
2024-05-08 16:20:49 +08:00
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
2024-05-07 17:41:21 +08:00
} else {
2024-10-15 17:39:02 +08:00
const err: Error = new Error()
err.name = data.responseCode.toString()
err.message = '服务异常'
reject(err)
2024-05-07 17:41:21 +08:00
}
}).catch((err: Error) => {
2024-10-18 20:30:27 +08:00
console.info('=====>' + 'Error:' + JSON.stringify({ err: err, url: params.url, }));
2024-05-08 16:20:49 +08:00
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
2024-10-20 17:59:30 +08:00
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
2024-05-07 17:41:21 +08:00
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
2024-10-18 20:30:27 +08:00
} else {
2024-05-07 17:41:21 +08:00
reject(err)
2024-10-18 20:30:27 +08:00
}
2024-05-07 17:41:21 +08:00
});
});
}
2024-05-08 16:20:49 +08:00
private getUrl(url: string, query?: Record<string, string> | Object) {
let u = url
if (query) {
let q = query
if (typeof query === 'object') {
2024-10-22 16:10:15 +08:00
q = ToolsHelperForTS.classToRecord(query)
2024-05-08 16:20:49 +08:00
}
u = `${u}${u.indexOf('?') < 0 ? '?' : u.endsWith('$') ? '' : '&'}`
Object.entries(q).forEach((row) => {
2024-05-08 16:54:06 +08:00
if (row[1]) {
u = `${u}${row[0]}=${row[1] as string}&`
}
2024-05-08 16:20:49 +08:00
});
u = u.slice(0, u.length - 1)
}
return u
}
2024-10-21 19:54:10 +08:00
private getContent(data?: Record<string, string> | Object) {
if (!data) {
return undefined
}
2024-10-10 19:22:29 +08:00
let u = ''
let q = data
if (typeof data === 'object') {
2024-10-22 16:10:15 +08:00
q = ToolsHelperForTS.classToRecord(data)
2024-10-10 19:22:29 +08:00
}
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
}
2024-10-22 16:10:15 +08:00
2024-05-07 17:41:21 +08:00
}