赞
踩
在HarmonyOS开发中,我们如果有基于http协议调用后端api,来操作数据或者和后端进行数据提交的交互,就可以通过导入http库来实现基于http的数据请求。
和使用Web组件一样,使用网络资源我们首先要开启网络访问权限,在module.json5文件中添加:
- {
- "module" : {
- "requestPermissions":[
- {
- "name": "ohos.permission.INTERNET"
- }
- ]
- }
- }
具体的编码步骤是:导包==》创建httpRequest对象==》订阅请求头(可选)==》发起http请求==》处理响应结果。
- //1.导入http模块
- import http from '@ohos.net.http';
-
- //2.创建httpRequest对象
- let httpRequest = http.createHttp();
-
- //3.订阅请求头(可选)
- httpRequest.on('headersReceive', (header) => {
- console.info('header: ' + JSON.stringify(header));
- });
-
- //4.发起http请求
- let url = "https://EXAMPLE_URL";
- let promise = httpRequest.request(
- // 请求url地址
- url,
- {
- // 请求方式
- method: http.RequestMethod.POST,
- // 请求的额外数据。
- extraData: {
- "param1": "value1",
- "param2": "value2",
- },
- // 可选,默认为60s
- connectTimeout: 60000,
- // 可选,默认为60s
- readTimeout: 60000,
- // 开发者根据自身业务需要添加header字段
- header: {
- 'Content-Type': 'application/json'
- }
- });
-
-
- //5.处理响应结果
- promise.then((data) => {
- if (data.responseCode === http.ResponseCode.OK) {
- console.info('Result:' + data.result);
- console.info('code:' + data.responseCode);
- }
- }).catch((err) => {
- console.info('error:' + JSON.stringify(err));
- });
-
Done!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。