HttpHelper.ets 12 KB

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