Compare commits
No commits in common. "66cf9d1b5f927fc6573c1be0f1c5b61607821f8a" and "6315aadc470c3e9251ac72ceec0cab16213c5314" have entirely different histories.
66cf9d1b5f
...
6315aadc47
@ -1,23 +1,130 @@
|
|||||||
import http from "@ohos.net.http"
|
import http from '@ohos.net.http';
|
||||||
import convertxml from '@ohos.convertxml';
|
import convertxml from '@ohos.convertxml';
|
||||||
import { BusinessError } from "@ohos.base"
|
import prompt from '@ohos.prompt';
|
||||||
import promptAction from "@ohos.promptAction";
|
import Prompt from '@system.prompt';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author: Renjun Su
|
||||||
|
* @date: 2023/2/20
|
||||||
|
* @desc 接口请求封装
|
||||||
|
* @param {method}
|
||||||
|
* @param {xml} xml请求的数据 xml是字符串
|
||||||
|
* @param {data} post请求的数据
|
||||||
|
* @param {params} get请求的数据
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
export default async function tempRequest<T>(req: any): Promise<T> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let httpRequest = http.createHttp();
|
||||||
|
const { url, params = {}, data = {}, xml, method = 'get', host, isNewCenter = false } = req;
|
||||||
|
try {
|
||||||
|
const options = {
|
||||||
|
method: http.RequestMethod[method.toUpperCase()],
|
||||||
|
header: {
|
||||||
|
'Content-Type': xml ? 'text/xml' : 'application/json'
|
||||||
|
},
|
||||||
|
extraData: xml ? data : JSON.stringify(data),
|
||||||
|
connectTimeout: 15 * 1000
|
||||||
|
}
|
||||||
|
let paramsStr = Reflect.ownKeys(params).reduce((p: string, n: string) => (`${p}${n}=${params[n]}&`), '?') || '';
|
||||||
|
paramsStr = paramsStr.toString();
|
||||||
|
paramsStr = paramsStr.substring(0, paramsStr.length - 1)
|
||||||
|
let baseUrl = host ? host : globalThis.host
|
||||||
|
// let baseUrl=host?config.csptHost:config.host'
|
||||||
|
console.log('响应头地址1' + baseUrl, url, options.extraData.length)
|
||||||
|
// const {result,responseCode} = await
|
||||||
|
httpRequest.request(`${baseUrl}${url}${paramsStr}`, {
|
||||||
|
...options
|
||||||
|
})
|
||||||
|
.then(async (data) => {
|
||||||
|
const result = data.result
|
||||||
|
console.log('响应头地址' + JSON.stringify(result))
|
||||||
|
let res: any = xml ? xmlToJson(result, url) : result;
|
||||||
|
console.log('响应头地址' + JSON.stringify(res))
|
||||||
|
|
||||||
|
let resObj = null;
|
||||||
|
if (typeof res === "string") {
|
||||||
|
res = JSON.parse(res)
|
||||||
|
}
|
||||||
|
//处理中心服务code
|
||||||
|
if (res.Envelope) {
|
||||||
|
const msgXml = res.Envelope.Body.writeObjectOutResponse.return;
|
||||||
|
const dd = handleCenterCode(msgXml, isNewCenter);
|
||||||
|
httpRequest.destroy();
|
||||||
|
// @ts-ignore
|
||||||
|
resolve(dd)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!xml) {
|
||||||
|
if (res.head.resultCode === '0') {
|
||||||
|
httpRequest.destroy();
|
||||||
|
resolve(res)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
const resultMessage = res?.body?.resultMessage || res?.head?.resultMessage
|
||||||
|
Prompt.showToast({
|
||||||
|
message: decodeURIComponent(resultMessage),
|
||||||
|
duration: 3000
|
||||||
|
});
|
||||||
|
httpRequest.destroy();
|
||||||
|
reject(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let i in res) {
|
||||||
|
resObj = res[i].head
|
||||||
|
}
|
||||||
|
console.info('jiangsong:res in request' + url + JSON.stringify(resObj))
|
||||||
|
if (resObj.resultCode === '0') {
|
||||||
|
httpRequest.destroy();
|
||||||
|
resolve(res)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
Prompt.showToast({
|
||||||
|
message: decodeURIComponent(resObj.resultMessage),
|
||||||
|
duration: 3000
|
||||||
|
});
|
||||||
|
httpRequest.destroy();
|
||||||
|
reject(res)
|
||||||
|
}
|
||||||
|
}).catch(Error => {
|
||||||
|
console.info('test-error0' + url + ' error:resp: ' + JSON.stringify(Error.message))
|
||||||
|
Prompt.showToast({
|
||||||
|
message: Error?.message,
|
||||||
|
duration: 5000
|
||||||
|
});
|
||||||
|
reject(Error)
|
||||||
|
})
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.info('test-error' + url + ' error:resp: ' + JSON.stringify(e))
|
||||||
|
if (!e || !(e?.message)) {
|
||||||
|
httpRequest.destroy();
|
||||||
|
reject({
|
||||||
|
code: -1
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Prompt.showToast({
|
||||||
|
message: e?.message,
|
||||||
|
duration: 5000
|
||||||
|
});
|
||||||
|
reject({
|
||||||
|
code: e.code
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
interface RequestOption {
|
|
||||||
url: string
|
|
||||||
params: object
|
|
||||||
data: object | string
|
|
||||||
xml: boolean
|
|
||||||
method: http.RequestMethod
|
|
||||||
host?: string
|
|
||||||
isNewCenter?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const base: string = ""
|
|
||||||
|
|
||||||
function xmlToJSON(target: string): object {
|
//xml格式转JSON
|
||||||
let conv = new convertxml.ConvertXML()
|
function xmlToJson(result, url) {
|
||||||
const result: object = conv.convertToJSObject(target, {
|
console.log("xmlToJson begin", url);
|
||||||
|
let xmlOptions = {
|
||||||
trim: false,
|
trim: false,
|
||||||
declarationKey: "_declaration",
|
declarationKey: "_declaration",
|
||||||
instructionKey: "_instruction",
|
instructionKey: "_instruction",
|
||||||
@ -30,151 +137,115 @@ function xmlToJSON(target: string): object {
|
|||||||
typeKey: "_type",
|
typeKey: "_type",
|
||||||
nameKey: "_name",
|
nameKey: "_name",
|
||||||
elementsKey: "_elements",
|
elementsKey: "_elements",
|
||||||
})
|
"skipPreprocess": true
|
||||||
return transfer(result['_elements'])
|
}
|
||||||
|
|
||||||
|
let strXml = result.toString();
|
||||||
|
let conv = new convertxml.ConvertXML();
|
||||||
|
|
||||||
|
console.log("xmlToJson result.length = " + result.length);
|
||||||
|
console.log("xmlToJson result content = " + result);
|
||||||
|
// @ts-ignore
|
||||||
|
let { _elements: xmlArr } = conv.convertToJSObject(strXml, xmlOptions);
|
||||||
|
console.log("xmlToJson deeml begin");
|
||||||
|
let res = deeml(xmlArr);
|
||||||
|
console.log("xmlToJson end", url);
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
function transfer(target: Array<object>, name?: string): object {
|
//处理中心服务code
|
||||||
const result: object = new Object()
|
function handleCenterCode(msgXml, isNewCenter) {
|
||||||
|
//新监管
|
||||||
target.forEach((el: object) => {
|
|
||||||
const _elements: Array<object> = el['_elements']
|
|
||||||
if (el['_type'] === "element") {
|
|
||||||
if (_elements === undefined) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const jsonObj: object = result[el['_name']]
|
|
||||||
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 {
|
|
||||||
jsonObj[el['_name']] = _elements[0]["_text"]
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (jsonObj) {
|
|
||||||
handleCommonArray(transfer(el['_elements'], el['_name']))
|
|
||||||
} else {
|
|
||||||
jsonObj[el['_name']] = transfer(el['_elements'], el['_name'])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (el['_attributes']) {
|
|
||||||
result[name] = {
|
|
||||||
value: el['_text'],
|
|
||||||
attributes: el['__attributes']
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CenterCodeResult {
|
|
||||||
code: string
|
|
||||||
message?: string
|
|
||||||
keystr?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
function dealCenterCode(message: string, isNewCenter: boolean): CenterCodeResult {
|
|
||||||
if (isNewCenter) {
|
if (isNewCenter) {
|
||||||
const msg: object = JSON.parse(message);
|
const msg = JSON.parse(msgXml);
|
||||||
const result: object = msg?.['data'][0]?.result;
|
const result = msg?.data[0]?.result;
|
||||||
if (result) {
|
if (result) {
|
||||||
if (result['code'] != '1') {
|
const { code, message, retval } = result
|
||||||
|
if (code != '1') {
|
||||||
const rMessage = decodeURIComponent(message as string)
|
const rMessage = decodeURIComponent(message as string)
|
||||||
promptAction.showToast({
|
Prompt.showToast({
|
||||||
message: rMessage,
|
message: rMessage,
|
||||||
duration: 3000
|
duration: 3000
|
||||||
});
|
});
|
||||||
let returnResult: CenterCodeResult = {
|
return { code, message }
|
||||||
code: result['code'] as string,
|
|
||||||
message: result['message'] as string,
|
|
||||||
}
|
|
||||||
return returnResult
|
|
||||||
} else {
|
} else {
|
||||||
let returnResult: CenterCodeResult = {
|
return { code, keystr: retval }
|
||||||
code: result['code'] as string,
|
|
||||||
keystr: result['retval'] as string,
|
|
||||||
}
|
|
||||||
return returnResult
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//正则匹配code message字段
|
||||||
|
const [code, message, keystr] =
|
||||||
|
[/<code>(.*)<\/code>/i, /<message>(.*)<\/message>/i, /<keystr>(.*)<\/keystr>/i].map(pattern => {
|
||||||
|
const patternArr = pattern.exec(msgXml);
|
||||||
|
return patternArr && patternArr[1]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (code != '1') {
|
||||||
|
prompt.showToast({
|
||||||
|
message: decodeURIComponent(message as string),
|
||||||
|
duration: 3000
|
||||||
|
});
|
||||||
|
// globalThis.type='1'
|
||||||
|
// globalThis.title=decodeURIComponent(message as string)
|
||||||
|
// globalThis.errorDialog.open()
|
||||||
|
return { code, message: decodeURIComponent(message) }
|
||||||
|
} else {
|
||||||
|
return { code, keystr, message }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Request<T>(options: RequestOption): Promise<T> {
|
//JSON转xml格式
|
||||||
return new Promise((resolve, reject) => {
|
const deeml = (elements, _name?) => {
|
||||||
const instance = http.createHttp()
|
const json = {}
|
||||||
const baseURL = options.host || base
|
|
||||||
|
|
||||||
instance.request(baseURL + options.url, {
|
elements.map(ele => {
|
||||||
method: options.method,
|
const _elements = ele._elements
|
||||||
header: {
|
if (ele._type === 'element') {
|
||||||
"Content-Type": options.xml ? "text/xml" : 'application/json'
|
if (_elements == undefined) {
|
||||||
},
|
|
||||||
extraData: options.xml ? options.data : JSON.stringify(options.data)
|
|
||||||
}).then(async data => {
|
|
||||||
let result = options.xml ? xmlToJSON(data.result as string) : data.result
|
|
||||||
let resObj: object
|
|
||||||
if (typeof result === 'string') {
|
|
||||||
result = JSON.parse(result)
|
|
||||||
}
|
|
||||||
if (result['Envelope']) {
|
|
||||||
const msgXml: string = result['Envelope']['Body']['writeObjectOutResponse']['return'];
|
|
||||||
resolve(dealCenterCode(msgXml, options.isNewCenter) as T)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!options.xml) {
|
const thisJson = json[ele._name]
|
||||||
if (result['head']['resultCode'] === '0') {
|
if (_elements && _elements.length === 1 && _elements[0]._type === 'text') {
|
||||||
resolve(result as T)
|
// 如果值存在了
|
||||||
return
|
if (thisJson) {
|
||||||
|
handleCommonArr(_elements[0]._text)
|
||||||
} else {
|
} else {
|
||||||
const resultMessage: string = result?.['body']?.['resultMessage'] || result?.['head']?.['resultMessage']
|
json[ele._name] = _elements[0]._text
|
||||||
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 {
|
} else {
|
||||||
promptAction.showToast({
|
if (thisJson) {
|
||||||
message: decodeURIComponent(resObj['resultMessage']),
|
handleCommonArr(deeml(ele._elements, ele._name))
|
||||||
duration: 3000
|
} else {
|
||||||
});
|
json[ele._name] = deeml(ele._elements, ele._name)
|
||||||
reject(result)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}).catch((err: BusinessError) => {
|
//通用处理重复标签
|
||||||
if (!err || !(err?.message)) {
|
function handleCommonArr(obj) {
|
||||||
reject({
|
if (thisJson) {
|
||||||
code: -1
|
if (Array.isArray(thisJson)) {
|
||||||
})
|
json[ele._name].push(obj)
|
||||||
|
} else {
|
||||||
|
json[ele._name] = [json[ele._name], obj]
|
||||||
}
|
}
|
||||||
promptAction.showToast({
|
} else {
|
||||||
message: err?.message,
|
json[ele._name] = obj
|
||||||
duration: 5000
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
//标签上有属性
|
||||||
|
if (ele._attributes) {
|
||||||
|
json[_name] = {
|
||||||
|
value: ele._text,
|
||||||
|
attributes: ele.__attributes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
reject({
|
return json
|
||||||
code: err.code
|
};
|
||||||
})
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
instance.destroy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user