import http from '@ohos.net.http'; import convertxml from '@ohos.convertxml'; import { BusinessError } from '@ohos.base'; import promptAction from '@ohos.promptAction'; import { RequestTag } from '../config'; interface RequestOption { url: string data?: object | string xml: boolean method: http.RequestMethod host?: string isNewCenter?: boolean timeout?: number } function xmlToJSON(target: string): object { let conv = new convertxml.ConvertXML() const result: object = conv.convertToJSObject(target, { trim: false, declarationKey: "_declaration", instructionKey: "_instruction", attributesKey: "_attributes", textKey: "_text", cdataKey: "_cdata", doctypeKey: "_doctype", commentKey: "_comment", parentKey: "_parent", typeKey: "_type", nameKey: "_name", elementsKey: "_elements", }) return transfer(result['_elements']) } function setObj(target: Record, key: string, value: object) { target[key] = value } function transfer(target: Array, name?: string): object { const result: object = new Object() target.forEach((el: object) => { const _elements: Array = el['_elements'] if (el['_type'] === "element") { if (_elements === undefined) { return } const jsonObj: Record = result[el['_name']] as Record const handleCommonArray = (obj: object) => { if (Array.isArray(jsonObj)) { result[el['_name']].push(obj) } else { result[el['_name']] = [result[el['_name']], obj] } } if (_elements && _elements.length === 1 && _elements[0]['_type'] === 'text') { if (jsonObj) { handleCommonArray(_elements[0]['_text']) } else { setObj(jsonObj, el['_name'], _elements[0]["_text"]) // jsonObj[el['_name'] as string] = _elements[0]["_text"] as object } } else { if (jsonObj) { handleCommonArray(transfer(el['_elements'], el['_name'])) } else { setObj(jsonObj, el['_name'], transfer(el['_elements'], el['_name'])) // jsonObj[el['_name'] as string] = transfer(el['_elements'], el['_name']) } } } else if (el['_attributes'] && name) { result[name] = { value: el['_text'], attributes: el['__attributes'] } } }) return result } interface CenterCodeResult { code: string message?: string keystr?: string } function dealCenterCode(message: string, isNewCenter: boolean = false): CenterCodeResult | undefined { if (isNewCenter) { const msg: object = JSON.parse(message); const result: object = msg?.['data'][0]?.result; if (result) { if (result['code'] != '1') { const rMessage = decodeURIComponent(message as string) promptAction.showToast({ message: rMessage, duration: 3000 }); let returnResult: CenterCodeResult = { code: result['code'] as string, message: result['message'] as string, } return returnResult } else { let returnResult: CenterCodeResult = { code: result['code'] as string, keystr: result['retval'] as string, } return returnResult } } } return undefined } type RequestResult = Object | object | string | CenterCodeResult export default function Request(options: RequestOption): Promise { return new Promise((resolve, reject) => { const base: string = AppStorage.get("host") || "http://127.0.0.1" const instance = http.createHttp() const baseURL = options.host || base console.log(RequestTag, "基础url:", baseURL) instance.request(baseURL + options.url, { method: options.method, header: { "Content-Type": options.xml ? "text/xml" : 'application/json' }, extraData: options.xml ? options.data : JSON.stringify(options.data), readTimeout: options.timeout || 30 * 1000 }).then(async data => { console.log(RequestTag, options.url, "返回的数据", JSON.stringify(data)) let result = options.xml ? xmlToJSON(data.result as string) : data.result let resObj: object = new Object() if (typeof result === 'string') { result = JSON.parse(result) } if (result['Envelope'] !== undefined) { const msgXml: string = result['Envelope']['Body']['writeObjectOutResponse']['return']; resolve(dealCenterCode(msgXml, options.isNewCenter) as T) return } if (!options.xml) { if (result['head']['resultCode'] === '0') { resolve(result as T) return } else { const resultMessage: string = result?.['body']?.['resultMessage'] || result?.['head']?.['resultMessage'] promptAction.showToast({ message: decodeURIComponent(resultMessage), duration: 3000 }); reject(false) return } } Object.values(result).forEach((item: object) => { resObj = item['head'] }) if (resObj['resultCode'] === '0') { resolve(result as T) return } else { promptAction.showToast({ message: decodeURIComponent(resObj['resultMessage']), duration: 3000 }); reject(result) } }).catch((err: BusinessError) => { console.error(RequestTag, "出错的url:", options.url, "错误信息:", JSON.stringify(err)) if (!err || !(err?.message)) { reject({ code: -1 }) } promptAction.showToast({ message: err?.message, duration: 5000 }); reject({ code: err.code }) }) .finally(() => { instance.destroy() }) }) }