Browse Source

接口请求

徐勤民 11 months ago
parent
commit
52bd64d9b5
1 changed files with 72 additions and 53 deletions
  1. 72 53
      src/main/ets/http/HttpHelper.ts

+ 72 - 53
src/main/ets/http/HttpHelper.ts

@@ -2,6 +2,13 @@ import { ArrayList, HashMap } from '@kit.ArkTS';
 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 {
   private static instance: HttpHelper | null = null
 
@@ -48,35 +55,35 @@ export class HttpHelper {
    * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
    * @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) => {
 
-      if (this.concurrentList.getIndexOf(apiNo ?? url) === -1 && this.httpHandlerList.hasKey(apiNo ?? url)) {
-        this.httpHandlerList.get(apiNo ?? url).destroy()
-        this.httpHandlerList.remove(apiNo ?? url)
+      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 ?? url) === -1) {
-        this.httpHandlerList.set(apiNo ?? url, httpRequest)
+      if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
+        this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
       }
 
       const header = {
-        "Content-Type": "application/json",
-        "Accept": "application/json",
-        ...headers
+        "Content-Type": "application/json;charset=UTF-8",
+        // "Accept": "application/json",
+        ...params.headers
       }
-      console.log('>>>>>', '接口请求', JSON.stringify(header))
-      console.log('>>>>>', '接口请求', data)
-      console.log('>>>>>', '接口请求', url)
+      // console.log('>>>>>', '接口请求', JSON.stringify(header))
+      // console.log('>>>>>', '接口请求', data)
+      console.log('>>>>>', 'POST:', params.url)
 
-      httpRequest.request(url, {
+      httpRequest.request(this.getUrl(params.url, params.query), {
         method: http.RequestMethod.POST,
-        connectTimeout: 60000,
-        readTimeout: 60000,
+        connectTimeout: 20000,
+        readTimeout: 20000,
         header: header,
-        extraData: data
+        extraData: params.data
       })
         .then((data: http.HttpResponse) => {
           console.info('=====>' + 'Result:' + data.result as string);
@@ -87,17 +94,17 @@ export class HttpHelper {
           // 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 (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)
+            resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
           } else {
             reject('服务异常')
           }
         }).catch((err: Error) => {
-        if (this.httpHandlerList.hasKey(apiNo ?? url)) {
-          this.httpHandlerList.remove(apiNo ?? url)
+        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')
@@ -108,6 +115,7 @@ export class HttpHelper {
 
   }
 
+
   /**
    * get请求
    * @param url url地址
@@ -116,46 +124,31 @@ export class HttpHelper {
    * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
    * @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) => {
 
-      if (this.concurrentList.getIndexOf(apiNo ?? url) === -1 && this.httpHandlerList.hasKey(apiNo ?? url)) {
-        this.httpHandlerList.get(apiNo ?? url).destroy()
-        this.httpHandlerList.remove(apiNo ?? url)
+      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 ?? url) === -1) {
-        this.httpHandlerList.set(apiNo ?? url, httpRequest)
+      if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
+        this.httpHandlerList.set(apiNo ?? params.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)
+        ...params.headers
       }
+      console.log('>>>>>', 'GET:', params.url)
 
-      httpRequest.request(url, {
+      httpRequest.request(this.getUrl(params.url, params.query), {
         method: http.RequestMethod.GET,
-        connectTimeout: 60000,
-        readTimeout: 60000,
+        connectTimeout: 20000,
+        readTimeout: 20000,
         header: header,
+        extraData: params.data
       })
         .then((data: http.HttpResponse) => {
           // console.info('=====>' + 'Result:' + data.result as string);
@@ -166,17 +159,17 @@ export class HttpHelper {
           // 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 (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)
+            resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
           } else {
             reject('服务异常')
           }
         }).catch((err: Error) => {
-        if (this.httpHandlerList.hasKey(apiNo ?? url)) {
-          this.httpHandlerList.remove(apiNo ?? url)
+        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')
@@ -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;
+  }
 }