223 lines
6.9 KiB
Plaintext
223 lines
6.9 KiB
Plaintext
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';
|
|
import Prompt from '@system.prompt';
|
|
|
|
interface RequestOption {
|
|
url: string
|
|
data?: object | string
|
|
xml: boolean
|
|
method: http.RequestMethod
|
|
host?: string
|
|
isNewCenter?: boolean
|
|
timeout?: number
|
|
accept?: boolean
|
|
}
|
|
|
|
|
|
function xmlToJSON(target: string): object {
|
|
console.log("进入xml解析")
|
|
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",
|
|
})
|
|
console.log("xml解析完成", JSON.stringify(result))
|
|
return transfer(result['_elements'])
|
|
}
|
|
|
|
function setObj(target: Record<string, object>, key: string, value: object) {
|
|
target[key] = value
|
|
}
|
|
|
|
function transfer(target: Array<object>, name?: string): object {
|
|
const result: Record<string, ESObject> = {}; // 使用 Record 类型以便动态添加属性
|
|
target.forEach((el: ESObject) => {
|
|
const _elements: Array<object> = el['_elements'];
|
|
if (el['_type'] === "element") {
|
|
if (_elements === undefined) {
|
|
return;
|
|
}
|
|
const jsonObj: ESObject = result[el['_name']];
|
|
const handleCommonArray = (obj: object) => {
|
|
if (Array.isArray(jsonObj)) {
|
|
jsonObj.push(obj);
|
|
} else {
|
|
result[el['_name']] = [jsonObj, obj];
|
|
}
|
|
};
|
|
|
|
if (_elements && _elements.length && _elements[0]['_type'] === 'text') {
|
|
if (jsonObj) {
|
|
handleCommonArray(_elements[0]['_text']);
|
|
} else {
|
|
result[el['_name']] = _elements[0]['_text'];
|
|
}
|
|
} else {
|
|
if (jsonObj) {
|
|
handleCommonArray(transfer(el['_elements'], el['_name']));
|
|
} else {
|
|
result[el['_name']] = 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
|
|
}
|
|
}
|
|
}
|
|
const result = parseXml(message)
|
|
if (result.code != '1') {
|
|
Prompt.showToast({
|
|
message: decodeURIComponent(message as string),
|
|
duration: 3000
|
|
});
|
|
return { code: result.code, message: decodeURIComponent(result.message || "") } as CenterCodeResult
|
|
} else {
|
|
return result
|
|
}
|
|
}
|
|
|
|
function parseXml(xml: string) {
|
|
const codeRegex = new RegExp("<code>(.*?)<\\/code>");
|
|
const messageRegex = new RegExp("<message>(.*?)<\\/message>");
|
|
const keystrRegex = new RegExp("<keystr>(.*?)<\\/keystr>");
|
|
|
|
const codeMatch = xml.match(codeRegex);
|
|
const messageMatch = xml.match(messageRegex);
|
|
const keystrMatch = xml.match(keystrRegex);
|
|
|
|
return {
|
|
code: codeMatch ? codeMatch[1] : null,
|
|
message: messageMatch ? messageMatch[1] : null,
|
|
keystr: keystrMatch ? keystrMatch[1] : null,
|
|
} as CenterCodeResult;
|
|
}
|
|
|
|
type RequestResult = Object | object | string | CenterCodeResult
|
|
|
|
export default function Request<T extends RequestResult>(options: RequestOption): Promise<T> {
|
|
return new Promise((resolve, reject) => {
|
|
const base: string = options.host ? options.host : AppStorage.get<string>("host") || "http://127.0.0.1"
|
|
const instance = http.createHttp()
|
|
const baseURL = options.host || base
|
|
console.log(RequestTag, "基础url:", baseURL)
|
|
console.log(RequestTag, "参数", JSON.stringify(options.data))
|
|
instance.request(baseURL + options.url, {
|
|
method: options.method,
|
|
header: {
|
|
"Content-Type": options.xml ? "text/xml" : 'application/json',
|
|
"Accept": options.accept ? "application/json" : "*/*",
|
|
},
|
|
extraData: options.xml ? options.data : JSON.stringify(options.data),
|
|
readTimeout: options.timeout || 30 * 1000
|
|
}).then(async data => {
|
|
console.log(RequestTag, baseURL, options.url, "返回的数据", JSON.stringify(data))
|
|
console.log(RequestTag, baseURL, options.url, "入参", options.accept, "xml", options.xml)
|
|
let result = options.xml ? (options.accept ? data.result : xmlToJSON(data.result as string)) : data.result;
|
|
console.log("结束xml解析", JSON.stringify(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 || (options.xml && options.accept)) {
|
|
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:", baseURL, 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()
|
|
})
|
|
})
|
|
} |