HttpHelper.ets 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. usingCache: false,
  79. })
  80. .then((data: http.HttpResponse) => {
  81. if (showLog) {
  82. LogHelper.debug(`${apiNo}:\n ${data.result as string}`)
  83. LogHelper.print(data)
  84. }
  85. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  86. this.httpHandlerList.remove(apiNo ?? params.url)
  87. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  88. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  89. this.httpHandlerList.length)
  90. }
  91. if (data.responseCode === 200) {
  92. resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
  93. } else {
  94. const err: Error = new Error()
  95. err.name = data.responseCode.toString()
  96. err.message = '服务异常'
  97. reject(err)
  98. }
  99. }).catch((err: Error) => {
  100. LogHelper.error(JSON.stringify({ err: err, url: params.url, }))
  101. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  102. this.httpHandlerList.remove(apiNo ?? params.url)
  103. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  104. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  105. this.httpHandlerList.length)
  106. }
  107. if (err.message === 'Failed writing received data to disk/application') {
  108. const error: Error = new Error()
  109. error.name = 'cancel'
  110. error.message = err.message
  111. reject(error)
  112. } else {
  113. reject(err)
  114. }
  115. });
  116. });
  117. }
  118. /**
  119. * postForm请求
  120. * @param url url地址
  121. * @param headers
  122. * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
  123. * @returns
  124. */
  125. public postForm<T>(params: HttpParamsForm, apiNo?: string, showLog?: boolean): Promise<T> {
  126. return new Promise<T>((resolve, reject) => {
  127. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
  128. this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  129. this.httpHandlerList.get(apiNo ?? params.url).destroy()
  130. this.httpHandlerList.remove(apiNo ?? params.url)
  131. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  132. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  133. this.httpHandlerList.length)
  134. }
  135. let httpRequest = http.createHttp();
  136. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
  137. this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
  138. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  139. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  140. this.httpHandlerList.length)
  141. }
  142. const header = HttpHelperX.getHeaders("application/x-www-form-urlencoded;charset=UTF-8", params.headers)
  143. let data = HttpHelperX.getContent(params.data)
  144. if (showLog) {
  145. LogHelper.debug(`postForm:${apiNo}\n`, JSON.stringify(params))
  146. }
  147. httpRequest.request(HttpHelperX.getUrl(params.url, params.query), {
  148. method: http.RequestMethod.POST,
  149. connectTimeout: 20000,
  150. readTimeout: 20000,
  151. header: header,
  152. usingCache: false,
  153. extraData: data ? encodeURI(data) : undefined
  154. })
  155. .then((data: http.HttpResponse) => {
  156. if (showLog) {
  157. LogHelper.debug(`${apiNo}:\n ${data.result as string}`)
  158. LogHelper.print(data)
  159. }
  160. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  161. this.httpHandlerList.remove(apiNo ?? params.url)
  162. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  163. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  164. this.httpHandlerList.length)
  165. }
  166. if (data.responseCode === 200) {
  167. resolve((typeof data.result === 'string' ? JSON.parse(data.result) : data.result) as T)
  168. } else {
  169. const err: Error = new Error()
  170. err.name = data.responseCode.toString()
  171. err.message = '服务异常'
  172. reject(err)
  173. }
  174. }).catch((err: Error) => {
  175. LogHelper.error(JSON.stringify({ err: err, url: params.url, }))
  176. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  177. this.httpHandlerList.remove(apiNo ?? params.url)
  178. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  179. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  180. this.httpHandlerList.length)
  181. }
  182. if (err.message === 'Failed writing received data to disk/application') {
  183. const error: Error = new Error()
  184. error.name = 'cancel'
  185. error.message = err.message
  186. reject(error)
  187. } else {
  188. reject(err)
  189. }
  190. });
  191. });
  192. }
  193. /**
  194. * get请求
  195. * @param url url地址
  196. * @param data 请求参数
  197. * @param headers
  198. * @param apiNo 请求标识,取消请求或者去重使用|考虑做自动重试使用
  199. * @returns
  200. */
  201. public get<T>(params: HttpParamsGet, apiNo?: string, showLog?: boolean): Promise<T> {
  202. return new Promise<T>((resolve, reject) => {
  203. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1 &&
  204. this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  205. this.httpHandlerList.get(apiNo ?? params.url).destroy()
  206. this.httpHandlerList.remove(apiNo ?? params.url)
  207. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  208. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  209. this.httpHandlerList.length)
  210. }
  211. let httpRequest = http.createHttp();
  212. if (this.concurrentList.getIndexOf(apiNo ?? params.url) === -1) {
  213. this.httpHandlerList.set(apiNo ?? params.url, httpRequest)
  214. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  215. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  216. this.httpHandlerList.length)
  217. }
  218. if (showLog) {
  219. LogHelper.debug(`GET:${apiNo}\n`, HttpHelperX.getUrl(params.url, params.query) + '\n',
  220. JSON.stringify(params.headers))
  221. }
  222. httpRequest.request(HttpHelperX.getUrl(params.url, params.query), {
  223. method: http.RequestMethod.GET,
  224. connectTimeout: 20000,
  225. readTimeout: 20000,
  226. header: params.headers,
  227. usingCache: false,
  228. // extraData: params.data
  229. })
  230. .then((data: http.HttpResponse) => {
  231. if (showLog) {
  232. LogHelper.debug(`${apiNo}:\n${data.result as string}`)
  233. LogHelper.print(data)
  234. }
  235. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  236. this.httpHandlerList.remove(apiNo ?? params.url)
  237. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  238. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  239. this.httpHandlerList.length)
  240. }
  241. if (data.responseCode === 200) {
  242. if (typeof data.result === 'string') {
  243. resolve(JSON.parse(data.result) as T)
  244. }else{
  245. resolve(data.result as T)
  246. }
  247. } else {
  248. const err: Error = new Error()
  249. err.name = data.responseCode.toString()
  250. err.message = '服务异常'
  251. reject(err)
  252. }
  253. }).catch((err: Error) => {
  254. LogHelper.error(JSON.stringify({ err: err, url: params.url, }))
  255. if (this.httpHandlerList.hasKey(apiNo ?? params.url)) {
  256. this.httpHandlerList.remove(apiNo ?? params.url)
  257. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  258. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  259. this.httpHandlerList.length)
  260. }
  261. if (err.message === 'Failed writing received data to disk/application') {
  262. const error: Error = new Error()
  263. error.name = 'cancel'
  264. error.message = err.message
  265. reject(error)
  266. } else {
  267. reject(err)
  268. }
  269. });
  270. });
  271. }
  272. clearHttp() {
  273. for (let handler of this.httpHandlerList.keys()) {
  274. this.cancel(handler)
  275. }
  276. }
  277. cancel(apiNo: string) {
  278. if (this.httpHandlerList.hasKey(apiNo)) {
  279. this.httpHandlerList.get(apiNo).destroy()
  280. this.httpHandlerList.remove(apiNo)
  281. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerList, this.httpHandlerList)
  282. SZYXLocalStorageHelper.storage.setOrCreate(SZYXLocalStorageKeys.HttpHandlerListLength,
  283. this.httpHandlerList.length)
  284. }
  285. }
  286. }