鸿蒙第三方开源官网:https://ohpm.openharmony.cn/#/cn/home
鸿蒙第三方开源源码:tpc_resource: 三方组件资源汇总
假设现在需要引入httpclient用来做网络请求,怎么做?
1.首先在module的oh-package.json5里面添加依赖
"dependencies": {
"@ohos/httpclient": "^2.0.0"
}
2.在module.json5中添加权限
"requestPermissions":[
{
"name": "ohos.permission.INTERNET"
}
]
3.ctrl/command+s后右上角会出现sync同步提示,点击即可,也可以在terminal执行命令
ohpm install
卸载是 ohpm uninstall @ohos/httpclient
4.添加后oh_modules里面就有了
5.先引用,比如在Index.ets文件中
import { FormEncoder, HttpClient, Logger, Request, TimeUnit } from '@ohos/httpclient';
6.调用
同步调用
objectivec
import {HttpClient,Request,RequestBody,TimeUnit,Logger} from '@ohos/httpclient';
let request = new Request.Builder()
.url("https://postman-echo.com/post")// 配置对应url
.post(RequestBody.create("test123"))
.addHeader("Content-Type", "text/plain")
.setEntryObj(new Weather()) //设置自定义请求的实体对象
.build();
this.client.newCall(request)
.executed() // 发起同步请求
.then(result => {
// 得到的是一个自定义请求类型的对象
Logger.info('Custom Request Result' + JSON.stringify(result));
})
.catch(err => {
Logger.error('Custom Request Error' + JSON.stringify(err));
});
异步调用
objectivec
let request = new Request.Builder()
.url("https://postman-echo.com/post") // 配置对应url
.post(RequestBody.create("test123"))
.addHeader("Content-Type", "text/plain")
.setEntryObj(new Weather(), true) //设置自定义请求的实体对象,异步需要传入true,否则执行的是常规请求
.build();
this.client.newCall(request)
// 发起异步请求
.enqueue((result) => {
// 得到的是一个自定义请求类型的对象
Logger.info('Custom Request Result == ' + JSON.stringify(result));
}, (error) => {
Logger.error('Custom Request error == ' + JSON.stringify(error));
})
文本提交
.addHeader("Content-Type", "text/plain")
见上面demo
form表单提交
.addHeader("Content-Type", "application/x-www-form-urlencoded")
objectivec
//请求后台签名使用httpclient
client: HttpClient = new HttpClient.Builder()
.setConnectTimeout(60, TimeUnit.SECONDS)
.setReadTimeout(60, TimeUnit.SECONDS)
.setWriteTimeout(60, TimeUnit.SECONDS)
.build();
let formEncoder = new FormEncoder.Builder()
.add("Version",this.orderInfo.Version)
.build();
let feBody = formEncoder.createRequestBody();
let request: Request = new Request.Builder()
.url(orderUrl)// 发送表单请求的时候,请配置header的Content-Type值为application/x-www-form-urlencoded
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.post(feBody)// .ca([this.certData])
.build();
this.client.newCall(request)
.execute()
.then((result) => {
this.visible = Visibility.None;
if (result) {
this.status = result.responseCode.toString();
}
if (result.result) {
this.content = result.result;
} else {
this.content = JSON.stringify(result);
}
Logger.info("onComplete -> Status : " + this.status);
Logger.info("onComplete -> Content : " + JSON.stringify(this.content));
})
.catch((error: Error) => {
// this.status = error.code.toString();
// this.content = error.data;
// Logger.error("onError -> Error : " + this.content);
Logger.error("onError -> Error : " + error.message);
});
xml格式文本提交
objectivec
let reqContent =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pay application=\"Query.Req\" version=\"" +
this.version + "\" pluginVersion=\"" + this.configVersion + "\" terminalModel=\"" + this.terminalModel +
"\" terminalOs=\"" + this.terminalOs + "\" pluginSerialNo=\"" + this.pluginSerialNo +
"\" terminalPhysicalNo=\"" + this.terminalPhysicalNo + "\"><merId>" + this.orderInfoObj.MerId +
"</merId><merDate>" + this.orderInfoObj.TranDate + "</merDate><merOrderNo>" + this.orderInfoObj.MerOrderNo +
"</merOrderNo></Pay>";
console.log("handlePayResult reqContent=" + reqContent);
let initStr = this.encodeReqStr(reqContent);
let request = new Request.Builder()
.url(this.serverUrl)// 配置对应url
.post(RequestBody.create(initStr))
.addHeader("Content-Type", "text/x-markdown")
.addHeader("charset", "utf8")
.build();
this.client.newCall(request)// 发起异步请求
.enqueue((result: string) => {
// 得到的是一个自定义请求类型的对象
let jsonObj: Object | null = JSON.parse(JSON.stringify(result));
let commObj = (jsonObj as Record<string, string>);
Logger.info('handlePayResult json result == ' + JSON.stringify(result));
Logger.info("handlePayResult record result=" + commObj["result"]);
let httpResp = this.decodeResp(this.aesKey, commObj["result"]);
//调用接口成功
if (httpResp.respCode == "0000") {
result = httpResp.netResult;
let start: number = httpResp.netResult.indexOf("<respCode>");
let end: number = httpResp.netResult.indexOf("</respCode>");
let respCode = httpResp.netResult.substring(start + 10, end);
payResult.respCode = respCode;
if (payResult.respCode == "0000") {
payResult.respMsg = "支付成功!";
} else {
let start1: number = httpResp.netResult.indexOf("<respDesc>");
let end1: number = httpResp.netResult.indexOf("</respDesc>");
let respMsg = httpResp.netResult.substring(start1 + 10, end1);
payResult.respMsg = respMsg;
}
} else {
payResult.respCode = httpResp.respCode;
payResult.respMsg = httpResp.respMsg;
}
callback(cpPayResult);
}, (error: BusinessError) => {
Logger.error('handlePayResult error == ' + JSON.stringify(error));
payResult.respCode = error.code.toString();
payResult.respMsg = error.message;
callback(payResult);
})
Logger.info("queryOrder异步请求开始");
具体用法请参考