HttpHelper.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import { ArrayList, HashMap } from '@kit.ArkTS';
  2. import http from '@ohos.net.http';
  3. type HttpParamsGet = {
  4. url: string
  5. query?: Record<string, string> | Object
  6. headers?: Record<string, string>
  7. }
  8. type HttpParamsPost = {
  9. url: string
  10. data?: Object
  11. query?: Record<string, string> | Object
  12. headers?: Record<string, string>
  13. }
  14. type HttpParamsForm = {
  15. url: string
  16. data?: Record<string, string> | Object
  17. query?: Record<string, string> | Object
  18. headers?: Record<string, string>
  19. }
  20. export class HttpHelper {
  21. private static instance: HttpHelper | null = null
  22. // 单例模式
  23. static get() {
  24. // 判断系统是否已经有单例了
  25. if (HttpHelper.instance === null) {
  26. HttpHelper.instance = new HttpHelper()
  27. }
  28. return HttpHelper.instance
  29. }
  30. //请求中队列
  31. private httpHandlerList = new HashMap<string, http.HttpRequest>();
  32. // 并发白名单,这个名单里面的api,重复请求不会取消
  33. private concurrentList = new ArrayList<string>();
  34. constructor() {
  35. this.httpHandlerList = new HashMap<string, http.HttpRequest>();
  36. this.concurrentList.clear()
  37. }
  38. /**
  39. * 添加并发白名单
  40. * @param apiNo
  41. */
  42. public addConcurrent(apiNo: string) {
  43. if (this.concurrentList.getIndexOf(apiNo) === -1) {
  44. this.concurrentList.add(apiNo)
  45. }
  46. }
  47. public removeConcurrent(apiNo: string) {
  48. if (this.concurrentList.getIndexOf(apiNo) !== -1) {
  49. this.concurrentList.remove(apiNo)
  50. }
  51. }
  52. /**
  53. * postJson请求
  54. * @param url url地址
  55. * @param headers
  56. * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
  57. * @returns
  58. */
  59. public postJson<T>(params: HttpParamsPost, apiNo?: string): Promise<T> {
  60. return new Promise<T>((resolve, reject) => {
  61. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 && this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  62. this.httpHandlerList.get(apiNo ?? params.url).destroy()
  63. this.httpHandlerList.remove(apiNo ?? params.url)
  64. }
  65. let httpRequest = http.createHttp();
  66. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
  67. this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
  68. }
  69. const header = {
  70. "Content-Type": "application/json;charset=UTF-8",
  71. // "Accept": "application/json",
  72. ...params.headers
  73. }
  74. console.log('=====>', 'POST:', JSON.stringify(params))
  75. // console.log('=====>', '接口请求', JSON.stringify(header))
  76. // console.log('=====>', '接口请求', data)
  77. httpRequest.request(this.getUrl(params.url, params.query), {
  78. method: http.RequestMethod.POST,
  79. connectTimeout: 20000,
  80. readTimeout: 20000,
  81. header: header,
  82. extraData: params.data
  83. })
  84. .then((data: http.HttpResponse) => {
  85. console.info('=====>' + 'Result:' + data.result as string);
  86. // console.info('=====>' + 'code:' + data.responseCode);
  87. // console.info('=====>' + 'type:' + JSON.stringify(data.resultType));
  88. // console.info('=====>' + 'header:' + JSON.stringify(data.header));
  89. // console.info('=====>' + 'cookies:' + data.cookies); // 自API version 8开始支持cookie
  90. // console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
  91. // console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
  92. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  93. this.httpHandlerList.remove(apiNo ?? params.url)
  94. }
  95. if (data.responseCode === 200) {
  96. resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
  97. } else {
  98. reject('服务异常')
  99. }
  100. }).catch((err: Error) => {
  101. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  102. this.httpHandlerList.remove(apiNo ?? params.url)
  103. }
  104. if (err.message === 'Failed writing received data to disk/application') {
  105. reject('cancel')
  106. } else
  107. reject(err)
  108. });
  109. });
  110. }
  111. /**
  112. * postForm请求
  113. * @param url url地址
  114. * @param headers
  115. * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
  116. * @returns
  117. */
  118. public postForm<T>(params: HttpParamsForm, apiNo?: string): Promise<T> {
  119. return new Promise<T>((resolve, reject) => {
  120. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 && this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  121. this.httpHandlerList.get(apiNo ?? params.url).destroy()
  122. this.httpHandlerList.remove(apiNo ?? params.url)
  123. }
  124. let httpRequest = http.createHttp();
  125. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
  126. this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
  127. }
  128. const header = {
  129. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  130. // "Accept": "application/json",
  131. ...params.headers
  132. }
  133. let data = this.getContent(params.data)
  134. console.log('=====>', 'POSTForm:', params.url)
  135. console.log('=====>', 'POSTForm:', JSON.stringify(header))
  136. console.log('=====>', 'POSTForm:', data)
  137. httpRequest.request(this.getUrl(params.url, params.query), {
  138. method: http.RequestMethod.POST,
  139. connectTimeout: 20000,
  140. readTimeout: 20000,
  141. header: header,
  142. extraData: data
  143. })
  144. .then((data: http.HttpResponse) => {
  145. console.info('=====>' + 'Result:' + data.result as string);
  146. // console.info('=====>' + 'code:' + data.responseCode);
  147. // console.info('=====>' + 'type:' + JSON.stringify(data.resultType));
  148. // console.info('=====>' + 'header:' + JSON.stringify(data.header));
  149. // console.info('=====>' + 'cookies:' + data.cookies); // 自API version 8开始支持cookie
  150. // console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
  151. // console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
  152. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  153. this.httpHandlerList.remove(apiNo ?? params.url)
  154. }
  155. if (data.responseCode === 200) {
  156. resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
  157. } else {
  158. reject('服务异常')
  159. }
  160. }).catch((err: Error) => {
  161. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  162. this.httpHandlerList.remove(apiNo ?? params.url)
  163. }
  164. if (err.message === 'Failed writing received data to disk/application') {
  165. reject('cancel')
  166. } else
  167. reject(err)
  168. });
  169. });
  170. }
  171. /**
  172. * get请求
  173. * @param url url地址
  174. * @param data 请求参数
  175. * @param headers
  176. * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
  177. * @returns
  178. */
  179. public get<T>(params: HttpParamsGet, apiNo?: string): Promise<T> {
  180. return new Promise<T>((resolve, reject) => {
  181. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 && this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  182. this.httpHandlerList.get(apiNo ?? params.url).destroy()
  183. this.httpHandlerList.remove(apiNo ?? params.url)
  184. }
  185. let httpRequest = http.createHttp();
  186. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
  187. this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
  188. }
  189. const header = {
  190. ...params.headers
  191. }
  192. console.log('=====>', 'GET:', this.getUrl(params.url, params.query))
  193. httpRequest.request(this.getUrl(params.url, params.query), {
  194. method: http.RequestMethod.GET,
  195. connectTimeout: 20000,
  196. readTimeout: 20000,
  197. header: header,
  198. // extraData: params.data
  199. })
  200. .then((data: http.HttpResponse) => {
  201. // console.info('=====>' + 'Result:' + data.result as string);
  202. // console.info('=====>' + 'code:' + data.responseCode);
  203. // console.info('=====>' + 'type:' + JSON.stringify(data.resultType));
  204. // console.info('=====>' + 'header:' + JSON.stringify(data.header));
  205. // console.info('=====>' + 'cookies:' + data.cookies); // 自API version 8开始支持cookie
  206. // console.info('=====>' + 'header.content-Type:' + JSON.stringify(data.header));
  207. // console.info('=====>' + 'header.Status-Line:' + JSON.stringify(data.header));
  208. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  209. this.httpHandlerList.remove(apiNo ?? params.url)
  210. }
  211. if (data.responseCode === 200) {
  212. resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
  213. } else {
  214. reject('服务异常')
  215. }
  216. }).catch((err: Error) => {
  217. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  218. this.httpHandlerList.remove(apiNo ?? params.url)
  219. }
  220. if (err.message === 'Failed writing received data to disk/application') {
  221. reject('cancel')
  222. } else
  223. reject(err)
  224. });
  225. });
  226. }
  227. private getUrl(url: string, query?: Record<string, string> | Object) {
  228. let u = url
  229. if (query) {
  230. let q = query
  231. if (typeof query === 'object') {
  232. q = this.classToRecord(query)
  233. }
  234. u = `${u}${u.indexOf('?') < 0 ? '?' : u.endsWith('$') ? '' : '&'}`
  235. Object.entries(q).forEach((row) => {
  236. if (row[1]) {
  237. u = `${u}${row[0]}=${row[1] as string}&`
  238. }
  239. });
  240. u = u.slice(0, u.length - 1)
  241. }
  242. return u
  243. }
  244. private getContent(data: Record<string, string> | Object) {
  245. let u = ''
  246. let q = data
  247. if (typeof data === 'object') {
  248. q = this.classToRecord(data)
  249. }
  250. Object.entries(q).forEach((row) => {
  251. if (row[1]) {
  252. u = `${u}${row[0]}=${row[1] as string}&`
  253. }
  254. });
  255. u = u.slice(0, u.length - 1)
  256. return u
  257. }
  258. private classToRecord(obj: Object): Record<string, string> {
  259. const record: Record<string, string> = {} as Record<string, string>;
  260. for (const key in obj) {
  261. if (obj.hasOwnProperty(key)) {
  262. record[key] = obj[key];
  263. }
  264. }
  265. return record;
  266. }
  267. }