HarmonyOS鸿蒙Next中如何使用@ohos.net.http进行网络请求并处理数据?
HarmonyOS鸿蒙Next中如何使用@ohos.net.http进行网络请求并处理数据?
如何使用@ohos.net.http进行网络请求并处理数据?
在鸿蒙(HarmonyOS)中使用 @ohos.net.http 进行网络请求并处理数据的步骤如下:
1. 导入模块
import http from '@ohos.net.http';
2. 创建请求对象
let httpRequest = http.createHttp(); // 每个任务对应一个独立对象,不可复用
3. 订阅响应头事件(可选)
httpRequest.on('headersReceive', (header: Object) => {
console.info('header: ' + JSON.stringify(header)); // 响应头先于请求结果返回
});
4. 发起网络请求
httpRequest.request(
"https://example.com/api", // 替换为实际URL
{
method: http.RequestMethod.POST, // 支持 GET/POST/PUT/DELETE 等
header: {
'Content-Type': 'application/json'
},
extraData: { // POST请求时传递的请求体
key: "value"
},
expectDataType: http.HttpDataType.STRING, // 指定响应数据类型
connectTimeout: 60000, // 连接超时时间(毫秒)
readTimeout: 60000, // 读取超时时间(毫秒)
},
(err: Error, http.HttpResponse) => {
// 下一步:在此回调中处理响应数据
}
);
5. 处理响应数据 在回调函数中解析响应:
(err: Error, http.HttpResponse) => {
if (!err) {
// 成功时处理数据
console.info('响应码: ' + data.responseCode);
if (data.responseCode === 200) {
console.info('结果: ' + JSON.stringify(data.result)); // 获取响应体
console.info('响应头: ' + JSON.stringify(data.header));
console.info('Cookies: ' + JSON.stringify(data.cookies)); // API 8+ 支持
}
} else {
// 错误处理
console.error('请求失败: ' + JSON.stringify(err));
}
// 6. 清理资源
httpRequest.off('headersReceive'); // 取消订阅
httpRequest.destroy(); // 销毁请求对象
}
关键参数说明
| 参数 | 说明 |
|---|---|
method |
请求方法(http.RequestMethod.GET/POST等) |
extraData |
POST/PUT请求的请求体数据 |
expectDataType |
指定响应类型(http.HttpDataType.STRING/OBJECT/ARRAY_BUFFER) |
connectTimeout |
连接超时时间(默认60秒) |
readTimeout |
读取超时时间(默认60秒) |
完整示例(POST请求)
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
httpRequest.on('headersReceive', (header) => {
console.info('响应头: ' + JSON.stringify(header));
});
httpRequest.request(
"https://example.com/login",
{
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: { username: "admin", password: "123456" },
connectTimeout: 60000,
readTimeout: 60000
},
(err, data) => {
if (!err && data.responseCode === 200) {
let result = JSON.parse(data.result as string); // 转换JSON字符串
console.info('登录成功: ' + result.token);
} else {
console.error('请求失败: ' + JSON.stringify(err));
}
httpRequest.destroy();
}
);
注意事项
- 权限申请:在
module.json5中添加网络权限:"requestPermissions": [{ "name": "ohos.permission.INTERNET" }] - 资源释放:请求完成后必须调用
destroy()销毁对象。 - 响应类型:若需直接获取JSON对象,可将
expectDataType设为http.HttpDataType.OBJECT。 - 错误处理:需检查
err和responseCode双重条件确保请求成功。
更多关于HarmonyOS鸿蒙Next中如何使用@ohos.net.http进行网络请求并处理数据?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
核心概念解析
@ohos.net.http 模块 是鸿蒙OS官方提供的用于发起网络请求的库。它遵循标准的HTTP协议,支持GET、POST等多种请求方法。
核心API流程:
1、创建HTTP客户端:使用http.createHttp()方法创建一个HttpRequest对象。这个对象代表了一个会话,可以用来发送一个或多个请求。
2、发起请求:调用httpRequest.request(url, options)方法发起请求。
- url: 请求的目标API地址。
- options: 一个可选的配置对象,可以设置请求方法(method)、请求头(header)、期望的响应类型(expectDataType)等。对于GET请求,method可以省略,默认为GET。
3、处理异步响应:request方法返回一个Promise<HttpResponse>。这意味着它是一个异步操作,我们可以使用async/await语法来优雅地处理它。
- 成功:Promise会resolve一个HttpResponse对象。我们主要关心它的responseCode(状态码,如200表示成功)和result(响应体,通常是JSON字符串)。
- 失败:Promise会reject一个错误对象,我们可以用try…catch来捕获。
4、状态管理:为了在UI上反映网络请求的不同阶段(加载中、成功、失败),我们需要定义几个@State变量来管理这些状态。
使用场景
比如实现一个“用户列表”页面:
在页面加载时:显示一个“加载中…”的动画或文本。
在请求成功时:隐藏加载动画,将从服务器获取的用户列表数据渲染成一个列表。
在请求失败时:隐藏加载动画,显示一个错误提示,如“网络请求失败,请稍后重试”,并提供一个“重试”按钮。
实现效果


完整代码
import http from '@ohos.net.http'; // 1. 导入http模块
// 定义用户数据接口
interface User {
id: number;
name: string;
email: string;
phone: string;
}
@Entry
@Component
struct Index {
// 2. 定义管理网络请求状态的变量
[@State](/user/State) isLoading: boolean = true; // 是否正在加载
[@State](/user/State) errorMessage: string = ''; // 错误信息
[@State](/user/State) userList: User[] = []; // 用户列表数据
// 3. 在页面即将出现时,发起网络请求
aboutToAppear() {
this.fetchUserData();
}
// 封装网络请求逻辑
private async fetchUserData() {
this.isLoading = true; // 开始加载
this.errorMessage = ''; // 清空旧错误信息
try {
// 创建一个HttpRequest对象
let httpRequest = http.createHttp();
// 发起请求
let response = await httpRequest.request('https://jsonplaceholder.typicode.com/users', {
expectDataType: http.HttpDataType.OBJECT,
header: {
'Content-Type': 'application/json'
}
});
// 检查响应状态码
if (response.responseCode === 200 && response.result) {
// 请求成功,更新数据
this.userList = response.result as User[];
} else {
// 状态码非200,视为错误
this.errorMessage = `请求失败,状态码: ${response.responseCode}`;
}
// 当请求结束后,销毁HttpRequest对象
httpRequest.destroy();
} catch (error) {
// 捕获网络异常或其他错误
console.error(`网络请求异常: ${error}`);
this.errorMessage = '网络请求失败,请检查网络连接';
} finally {
// 无论成功还是失败,都结束加载状态
this.isLoading = false;
}
}
build() {
Column() {
Text('用户列表')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 20, bottom: 20 })
// 4. 根据不同状态渲染不同UI
if (this.isLoading) {
// 加载中状态
LoadingProgress()
.width(50)
.height(50)
.color('#007DFF')
Text('正在加载数据...')
.fontSize(16)
.margin({ top: 10 })
} else if (this.errorMessage) {
// 错误状态
Column({ space: 15 }) {
Image($r('app.media.startIcon')) // 假设你有一个错误图标
.width(60)
.height(60)
Text(this.errorMessage)
.fontSize(16)
.fontColor('#FF0000')
Button('重试')
.onClick(() => {
this.fetchUserData(); // 点击重试
})
}
} else {
// 成功状态,渲染列表
List({ space: 10 }) {
ForEach(this.userList, (user: User) => {
ListItem() {
Row() {
Column({ space: 5 }) {
Text(user.name)
.fontSize(18)
.fontWeight(FontWeight.Bold)
Text(user.email)
.fontSize(14)
.fontColor('#666666')
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
Text(user.phone)
.fontSize(14)
.fontColor('#999999')
}
.width('100%')
.padding(15)
.backgroundColor('#FFFFFF')
.borderRadius(8)
}
})
}
.layoutWeight(1)
.width('90%')
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
.backgroundColor('#F1F3F5')
}
}
在HarmonyOS Next中,使用@ohos.net.http进行网络请求需先导入模块:import http from '@ohos.net.http';。创建http.HttpRequest实例,通过request()方法发起请求,配置url、method等参数。处理响应数据在回调函数中完成,使用response.result获取返回结果。注意在module.json5中声明ohos.permission.INTERNET网络权限。
在HarmonyOS Next中,使用@ohos.net.http进行网络请求并处理数据是开发应用的基础能力。以下是核心步骤和代码示例:
1. 导入模块与权限声明
首先,在entry/src/main/module.json5文件中声明网络权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
在代码文件中导入http模块:
import { http } from '@kit.NetworkKit';
2. 创建HTTP请求实例
使用createHttp()方法创建请求对象:
let httpRequest = http.createHttp();
3. 发起网络请求
以GET请求为例,使用request()方法:
let url = 'https://example.com/api/data';
httpRequest.request(
url,
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
}
},
(err, data) => {
if (err) {
console.error('Request failed:', err.code, err.message);
return;
}
console.info('Response code:', data.responseCode);
console.info('Response data:', data.result.toString());
}
);
4. 处理响应数据
在回调函数中解析返回的JSON数据:
if (data.responseCode === http.ResponseCode.OK) {
try {
let result = JSON.parse(data.result.toString());
console.info('Parsed data:', result);
// 在此处更新UI或处理业务逻辑
} catch (e) {
console.error('JSON parse error:', e);
}
}
5. 释放资源
请求完成后及时释放资源:
httpRequest.destroy();
关键点说明:
- 请求方法:可通过
http.RequestMethod.GET/POST/PUT/DELETE指定 - 异步处理:
request()方法为异步操作,需在回调中处理结果 - 错误处理:必须检查
err对象和responseCode - 数据格式:
data.result为ArrayBuffer类型,需转换为字符串后再解析JSON
POST请求示例:
httpRequest.request(
url,
{
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify({ key: 'value' })
},
(err, data) => {
// 处理响应
}
);
以上流程涵盖了从权限配置到数据处理的完整网络请求实现。注意在实际开发中应将网络操作封装为独立模块,并做好异常处理和超时配置。

