接口请求

这个提交包含在:
徐勤民 2024-05-08 16:20:49 +08:00
父节点 096507cc42
当前提交 52bd64d9b5

查看文件

@ -2,6 +2,13 @@ import { ArrayList, HashMap } from '@kit.ArkTS';
import http from '@ohos.net.http'; import http from '@ohos.net.http';
type HttpParams = {
url: string
data?: string | Object | ArrayBuffer
query?: Record<string, string> | Object
headers?: Record<string, string>
}
export class HttpHelper { export class HttpHelper {
private static instance: HttpHelper | null = null private static instance: HttpHelper | null = null
@ -48,35 +55,35 @@ export class HttpHelper {
* @param apiNo 使|使 * @param apiNo 使|使
* @returns * @returns
*/ */
public post<T>(url: string, data: string | Object | ArrayBuffer | undefined, headers?: Record<string, string>, apiNo?: string): Promise<T> { public postJson<T>(params: HttpParams, apiNo?: string): Promise<T> {
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1 && this.httpHandlerList.hasKey(apiNo ?? url)) { if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 && this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.get(apiNo ?? url).destroy() this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? url) this.httpHandlerList.remove(apiNo ?? params.url)
} }
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1) { if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? url, httpRequest) this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
} }
const header = { const header = {
"Content-Type": "application/json", "Content-Type": "application/json;charset=UTF-8",
"Accept": "application/json", // "Accept": "application/json",
...headers ...params.headers
} }
console.log('>>>>>', '接口请求', JSON.stringify(header)) // console.log('>>>>>', '接口请求', JSON.stringify(header))
console.log('>>>>>', '接口请求', data) // console.log('>>>>>', '接口请求', data)
console.log('>>>>>', '接口请求', url) console.log('>>>>>', 'POST:', params.url)
httpRequest.request(url, { httpRequest.request(this.getUrl(params.url, params.query), {
method: http.RequestMethod.POST, method: http.RequestMethod.POST,
connectTimeout: 60000, connectTimeout: 20000,
readTimeout: 60000, readTimeout: 20000,
header: header, header: header,
extraData: data extraData: params.data
}) })
.then((data: http.HttpResponse) => { .then((data: http.HttpResponse) => {
console.info('=====>' + 'Result:' + data.result as string); console.info('=====>' + 'Result:' + data.result as string);
@ -87,8 +94,8 @@ export class HttpHelper {
// console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header)); // console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
// console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header)); // console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
if (this.httpHandlerList.hasKey(apiNo ?? url)) { if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? url) this.httpHandlerList.remove(apiNo ?? params.url)
} }
if (data.responseCode === 200) { if (data.responseCode === 200) {
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T) resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
@ -96,8 +103,8 @@ export class HttpHelper {
reject('服务异常') reject('服务异常')
} }
}).catch((err: Error) => { }).catch((err: Error) => {
if (this.httpHandlerList.hasKey(apiNo ?? url)) { if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? url) this.httpHandlerList.remove(apiNo ?? params.url)
} }
if (err.message === 'Failed writing received data to disk/application') { if (err.message === 'Failed writing received data to disk/application') {
reject('cancel') reject('cancel')
@ -108,6 +115,7 @@ export class HttpHelper {
} }
/** /**
* get请求 * get请求
* @param url url地址 * @param url url地址
@ -116,46 +124,31 @@ export class HttpHelper {
* @param apiNo 使|使 * @param apiNo 使|使
* @returns * @returns
*/ */
public get<T>(url: string, data: string | undefined, headers?: Object, apiNo?: string): Promise<T> { public get<T>(params: HttpParams, apiNo?: string): Promise<T> {
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1 && this.httpHandlerList.hasKey(apiNo ?? url)) { if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 && this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.get(apiNo ?? url).destroy() this.httpHandlerList.get(apiNo ?? params.url).destroy()
this.httpHandlerList.remove(apiNo ?? url) this.httpHandlerList.remove(apiNo ?? params.url)
} }
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
if (this.concurrentList.getIndexOf(apiNo ?? url) === -1) { if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
this.httpHandlerList.set(apiNo ?? url, httpRequest) this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
} }
const header = { const header = {
// "Content-Type": "application/json", ...params.headers
// "Accept": "application/json",
...headers
} }
// console.log('>>>>>', '接口请求', JSON.stringify(header)) console.log('>>>>>', 'GET:', params.url)
// console.log('>>>>>', '接口请求', data)
// console.log('>>>>>', '接口请求', url)
if (data) { httpRequest.request(this.getUrl(params.url, params.query), {
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, method: http.RequestMethod.GET,
connectTimeout: 60000, connectTimeout: 20000,
readTimeout: 60000, readTimeout: 20000,
header: header, header: header,
extraData: params.data
}) })
.then((data: http.HttpResponse) => { .then((data: http.HttpResponse) => {
// console.info('=====>' + 'Result:' + data.result as string); // console.info('=====>' + 'Result:' + data.result as string);
@ -166,8 +159,8 @@ export class HttpHelper {
// console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header)); // console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
// console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header)); // console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
if (this.httpHandlerList.hasKey(apiNo ?? url)) { if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? url) this.httpHandlerList.remove(apiNo ?? params.url)
} }
if (data.responseCode === 200) { if (data.responseCode === 200) {
resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T) resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
@ -175,8 +168,8 @@ export class HttpHelper {
reject('服务异常') reject('服务异常')
} }
}).catch((err: Error) => { }).catch((err: Error) => {
if (this.httpHandlerList.hasKey(apiNo ?? url)) { if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
this.httpHandlerList.remove(apiNo ?? url) this.httpHandlerList.remove(apiNo ?? params.url)
} }
if (err.message === 'Failed writing received data to disk/application') { if (err.message === 'Failed writing received data to disk/application') {
reject('cancel') reject('cancel')
@ -186,4 +179,30 @@ export class HttpHelper {
}); });
} }
private getUrl(url: string, query?: Record<string, string> | Object) {
let u = url
if (query) {
let q = query
if (typeof query === 'object') {
q = this.classToRecord(query)
}
u = `${u}${u.indexOf('?') < 0 ? '?' : u.endsWith('$') ? '' : '&'}`
Object.entries(q).forEach((row) => {
u = `${u}${row[0]}=${row[1] as string}&`
});
u = u.slice(0, u.length - 1)
}
return u
}
private classToRecord(obj: Object): Record<string, string> {
const record: Record<string, string> = {} as Record<string, string>;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
record[key] = obj[key];
}
}
return record;
}
} }