1、封装http 工具类
import { HKBasePch } from '../PCH/HKPCH';
import { authHeaderSign } from './authHeaderSign';
import deviceInfo from '@ohos.deviceInfo';
import http from '@ohos.net.http';
import { Logger } from '@hzw/logger';
export class httpAxios {
//HttpResponse
public static async bodyPost(params: Map<string, object>,url:string, resultBlock:(res:http.HttpResponse) => void) {
// 拼接设备基础参数
let p = createHttp(params)
Logger.w("传参 ======")
console.dir(p)
// 拼接url 域名
let baseUrl = HKBasePch.Base_URL.toString() + url
let resp = await http.createHttp()
.request(baseUrl,await httpAxios.createParams(p))
Logger.w("返回参数: ====== ")
console.dir(resp.result)
resultBlock(resp)
// if (resp.responseCode == http.ResponseCode.OK){
// resultBlock(resp)
// }else{
// resultBlock(resp)
// }
}
/**
* 设置Header 和 超时时间
* */
public static async createParams(params: Map<string, object>): Promise<http.HttpRequestOptions> {
let p = createHttp(params)
let header: Map<string, string> = new Map();
header.set('Content-Type', 'application/json')
header.set('Authorization', authHeaderSign.authSign(JSON.stringify(p)))
Logger.w("鉴权信息: Authorization ======")
console.dir(authHeaderSign.authSign(JSON.stringify(p)))
let options: http.HttpRequestOptions = {
method: http.RequestMethod.POST,
extraData: p,
expectDataType: http.HttpDataType.OBJECT,
header: {
'Content-Type': 'application/json',
'Authorization': authHeaderSign.authSign(JSON.stringify(p))
},
// 可选,默认为60s
connectTimeout: 30000,
// 可选,默认为60s
readTimeout: 30000,
usingProxy: true,
}
return options
}
}
function createHttp(map?: Map<string, object>) {
let params: Map<string, object>;
if (map == null) {
params = new Map<string, object>();
} else {
params = map;
}
params["zyOs"] = "hmOS";
params["zyOsVersion"] = deviceInfo.displayVersion;
params["zyModel"] = deviceInfo.productModel;
params["zyBrand"] = deviceInfo.brand;
params["abiList"] = deviceInfo.abiList;
params["osFullName"] = deviceInfo.osFullName;
params["deviceType"] = deviceInfo.deviceType;
return params;
}
2、调用方法
httpAxios.bodyPost(params,url,(rep) =>{
if (rep.responseCode == http.ResponseCode.OK){
}else{
}
})