在HarmonyOS中进行网络请求开发时,可以使用"@ohos.net.http"库,该库支持常见的HTTP方法,能够满足大多数应用或元服务的需求。
接下来,我们将通过http库,对其进行二次封装,并向后台发送请求,完成banner数据的获取。
一、基本使用
1.1 导入模块
import http from '@ohos.net.http'
1.2 http请求数据
首先,我们先看下@ohos.net.http的基本用法,使用http模块发送一个GET请求,处理响应。示例代码如下:
import http from '@ohos.net.http';
// 创建 HTTP 请求对象
let httpRequest = http.createHttp();
// 发送 GET 请求
httpRequest.request(
"https://api.example.com/data",
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
}
},
(err, data) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Response Code:', data.responseCode);
console.log('Response Data:', data.result);
}
}
);
1.3 HttpRequestOptions
参数如下表:
名称 |
类型 |
描述 |
method |
RequestMethod |
请求方式:GET、POST、PUT、DELETE等 |
extraData |
string|Object |
请求参数 |
header |
Object |
请求字段 |
connectTimeout |
number |