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

189 行
6.2 KiB
TypeScript

2024-05-07 17:41:21 +08:00
import { ArrayList, HashMap } from '@kit.ArkTS';
import http from '@ohos.net.http';
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>();
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 data
* @param headers
* @param apiNo 使|使
* @returns
*/
public post<T>(url: string, data: string | undefined, headers?: Object, apiNo?: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1 && this.httpHandlerList.hasKey(apiNo ?? url)) {
this.httpHandlerList.get(apiNo ?? url).destroy()
this.httpHandlerList.remove(apiNo ?? url)
}
let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1) {
this.httpHandlerList.set(apiNo ?? url, httpRequest)
}
const header = {
"Content-Type": "application/json",
"Accept": "application/json",
...headers
}
console.log('>>>>>', '接口请求', JSON.stringify(header))
console.log('>>>>>', '接口请求', data)
console.log('>>>>>', '接口请求', url)
httpRequest.request(url, {
method: http.RequestMethod.POST,
connectTimeout: 60000,
readTimeout: 60000,
header: header,
extraData: data
})
.then((data: http.HttpResponse) => {
console.info('=====>' + 'Result:' + data.result as string);
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 ?? url)) {
this.httpHandlerList.remove(apiNo ?? url)
}
if (data.responseCode === 200) {
resolve(JSON.parse(data.result as string) as T)
} else {
reject('服务异常')
}
}).catch((err: Error) => {
if (this.httpHandlerList.hasKey(apiNo ?? url)) {
this.httpHandlerList.remove(apiNo ?? url)
}
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>(url: string, data: string | undefined, headers?: Object, apiNo?: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1 && this.httpHandlerList.hasKey(apiNo ?? url)) {
this.httpHandlerList.get(apiNo ?? url).destroy()
this.httpHandlerList.remove(apiNo ?? url)
}
let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1) {
this.httpHandlerList.set(apiNo ?? url, httpRequest)
}
const header = {
// "Content-Type": "application/json",
// "Accept": "application/json",
...headers
}
// console.log('>>>>>', '接口请求', JSON.stringify(header))
// console.log('>>>>>', '接口请求', data)
// console.log('>>>>>', '接口请求', url)
if (data) {
url = `${url}?`
const json = JSON.parse(data)
for (let jsonKey in json) {
const value = json[jsonKey]
if (value) {
url = `${url}${jsonKey}=${json[jsonKey]}&`
}
}
url = url.slice(0, url.length - 1)
}
httpRequest.request(url, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: header,
})
.then((data: http.HttpResponse) => {
console.info('=====>' + 'Result:' + data.result as string);
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 ?? url)) {
this.httpHandlerList.remove(apiNo ?? url)
}
if (data.responseCode === 200) {
resolve(JSON.parse(data.result as string) as T)
} else {
reject('服务异常')
}
}).catch((err: Error) => {
if (this.httpHandlerList.hasKey(apiNo ?? url)) {
this.httpHandlerList.remove(apiNo ?? url)
}
if (err.message === 'Failed writing received data to disk/application') {
reject('cancel')
} else
reject(err)
});
});
}
}