HarmonyOSBaseLibs/src/main/ets/http/HttpHelper.ets
徐勤民 9a2f82c33c feat(app): 添加应用崩溃恢复功能并优化网络请求
- 新增 MyAbilityStage 类,实现应用崩溃恢复功能
- 在 ApiElem接口中添加 showLog 字段,用于控制请求日志输出
- 重构 HttpHelper 类,提取公共方法到 HttpHelperX 类
- 优化网络请求方法,增加日志输出和错误处理
- 新增 Base64Helper 和 CharHelper 工具类
2024-10-31 12:23:46 +08:00

290 行
11 KiB
Plaintext

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

import { ArrayList, HashMap } from '@kit.ArkTS';
import http from '@ohos.net.http';
import { LogHelper } from '../../../../Index';
import { SZYXLocalStorageHelper } from '../utils/SZYXLocalStorageHelper';
import { SZYXLocalStorageKeys } from '../utils/SZYXLocalStorageKeys';
import { HttpHelperX, HttpParamsForm, HttpParamsGet, HttpParamsPost } from './HttpHelperX';
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>();
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength, this.httpHandlerList.length)
this.concurrentList.clear()
}
/**
* 添加并发白名单
* @param apiNo
*/
public addConcurrent(apiNo?: string) {
if (!apiNo) {
return
}
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
*/
public postJson<T>(params: HttpParamsPost, apiNo?: string, showLog?: boolean): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
const header = HttpHelperX.getHeaders("application/json;charset=UTF-8", params.headers)
if (showLog) {
LogHelper.debug(`postJson${apiNo}\n`, JSON.stringify(params))
}
httpRequest.request(HttpHelperX.getUrl(params.url, params.query), {
method: http.RequestMethod.POST,
connectTimeout: 20000,
readTimeout: 20000,
header: header,
extraData: params.data
})
.then((data: http.HttpResponse) => {
if (showLog) {
LogHelper.debug(`${apiNo}:\n ${data.result as string}`)
LogHelper.print(data)
}
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (data.responseCode === 200) {
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
} else {
const err: Error = new Error()
err.name = data.responseCode.toString()
err.message = '服务异常'
reject(err)
}
}).catch((err: Error) => {
LogHelper.error(JSON.stringify({ err: err, url: params.url, }))
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
} else {
reject(err)
}
});
});
}
/**
* postForm请求
* @param url url地址
* @param headers
* @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
* @returns
*/
public postForm<T>(params: HttpParamsForm, apiNo?: string, showLog?: boolean): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
const header = HttpHelperX.getHeaders("application/x-www-form-urlencoded;charset=UTF-8", params.headers)
let data = HttpHelperX.getContent(params.data)
if (showLog) {
LogHelper.debug(`postForm${apiNo}\n`, JSON.stringify(params))
}
httpRequest.request(HttpHelperX.getUrl(params.url, params.query), {
method: http.RequestMethod.POST,
connectTimeout: 20000,
readTimeout: 20000,
header: header,
extraData: data ? encodeURI(data) : undefined
})
.then((data: http.HttpResponse) => {
if (showLog) {
LogHelper.debug(`${apiNo}:\n ${data.result as string}`)
LogHelper.print(data)
}
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (data.responseCode === 200) {
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
} else {
const err: Error = new Error()
err.name = data.responseCode.toString()
err.message = '服务异常'
reject(err)
}
}).catch((err: Error) => {
LogHelper.error(JSON.stringify({ err: err, url: params.url, }))
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
} else {
reject(err)
}
});
});
}
/**
* get请求
* @param url url地址
* @param data 请求参数
* @param headers
* @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
* @returns
*/
public get<T>(params: HttpParamsGet, apiNo?: string, showLog?: boolean): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (showLog) {
LogHelper.debug(`GET${apiNo}\n`, HttpHelperX.getUrl(params.url, params.query) + '\n',
JSON.stringify(params.headers))
}
httpRequest.request(HttpHelperX.getUrl(params.url, params.query), {
method: http.RequestMethod.GET,
connectTimeout: 20000,
readTimeout: 20000,
header: params.headers,
// extraData: params.data
})
.then((data: http.HttpResponse) => {
if (showLog) {
LogHelper.debug(`${apiNo}:\n${data.result as string}`)
LogHelper.print(data)
}
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (data.responseCode === 200) {
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
} else {
const err: Error = new Error()
err.name = data.responseCode.toString()
err.message = '服务异常'
reject(err)
}
}).catch((err: Error) => {
LogHelper.error(JSON.stringify({ err: err, url: params.url, }))
if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? params.url)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
this.httpHandlerList.length)
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
} else {
reject(err)
}
});
});
}
}