123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 |
- import { ArrayList, HashMap } from '@kit.ArkTS';
- import http from '@ohos.net.http';
- type HttpParamsGet = {
- url: string
- query?: Record<string, string> | Object
- headers?: Record<string, string>
- }
- type HttpParamsPost = {
- url: string
- data?: Object
- query?: Record<string, string> | Object
- headers?: Record<string, string>
- }
- type HttpParamsForm = {
- url: string
- data?: Record<string, string> | Object
- query?: Record<string, string> | Object
- headers?: Record<string, string>
- }
- 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 headers
- * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
- * @returns
- */
- public postJson<T>(params: HttpParamsPost, apiNo?: string): 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)
- }
- let httpRequest = http.createHttp();
- if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
- this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
- }
- const header = {
- "Content-Type": "application/json;charset=UTF-8",
- // "Accept": "application/json",
- ...params.headers
- }
- console.log('=====>', 'POST:', JSON.stringify(params))
- // console.log('=====>', '接口请求', JSON.stringify(header))
- // console.log('=====>', '接口请求', data)
- httpRequest.request(this.getUrl(params.url, params.query), {
- method: http.RequestMethod.POST,
- connectTimeout: 20000,
- readTimeout: 20000,
- header: header,
- extraData: params.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 ?? params.url)) {
- this.httpHandlerList.remove(apiNo ?? params.url)
- }
- if (data.responseCode === 200) {
- resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
- } else {
- reject('服务异常')
- }
- }).catch((err: Error) => {
- if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
- this.httpHandlerList.remove(apiNo ?? params.url)
- }
- 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): 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)
- }
- let httpRequest = http.createHttp();
- if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
- this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
- }
- const header = {
- "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
- // "Accept": "application/json",
- ...params.headers
- }
- let data = this.getContent(params.data)
- 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,
- 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 ?? params.url)) {
- this.httpHandlerList.remove(apiNo ?? params.url)
- }
- if (data.responseCode === 200) {
- resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
- } else {
- reject('服务异常')
- }
- }).catch((err: Error) => {
- if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
- this.httpHandlerList.remove(apiNo ?? params.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>(params: HttpParamsGet, apiNo?: string): 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)
- }
- let httpRequest = http.createHttp();
- if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
- this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
- }
- const header = {
- ...params.headers
- }
- console.log('=====>', 'GET:', this.getUrl(params.url, params.query))
- httpRequest.request(this.getUrl(params.url, params.query), {
- method: http.RequestMethod.GET,
- connectTimeout: 20000,
- readTimeout: 20000,
- header: header,
- // extraData: params.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 ?? params.url)) {
- this.httpHandlerList.remove(apiNo ?? params.url)
- }
- if (data.responseCode === 200) {
- resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
- } else {
- reject('服务异常')
- }
- }).catch((err: Error) => {
- if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
- this.httpHandlerList.remove(apiNo ?? params.url)
- }
- if (err.message === 'Failed writing received data to disk/application') {
- reject('cancel')
- } else
- reject(err)
- });
- });
- }
- 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) => {
- if (row[1]) {
- u = `${u}${row[0]}=${row[1] as string}&`
- }
- });
- u = u.slice(0, u.length - 1)
- }
- return u
- }
- private getContent(data: Record<string, string> | Object) {
- let u = ''
- let q = data
- if (typeof data === 'object') {
- q = this.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
- }
- 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;
- }
- }
|