鸿蒙网络请求与数据加载
📅 2025-05-11 · ⏱ 15 分钟 · 网络
网络请求是现代应用的核心能力。本文介绍如何在 HarmonyOS 中使用 @ohos.net.http 进行 HTTP 请求。
一、GET 请求
import { http } from "@kit.NetworkKit"
async function fetchUserList() {
const httpRequest = http.createHttp()
try {
const response = await httpRequest.request(
"https://api.example.com/users",
{
method: http.RequestMethod.GET,
header: {
"Content-Type": "application/json",
"Authorization": "Bearer your_token"
},
connectTimeout: 10000,
readTimeout: 10000
}
)
if (response.responseCode === 200) {
const data = JSON.parse(response.result as string)
console.log("用户列表:" + JSON.stringify(data))
return data
} else {
console.error("请求失败:" + response.responseCode)
}
} catch (err) {
console.error("网络错误:" + JSON.stringify(err))
} finally {
httpRequest.destroy()
}
}
二、POST 请求
async function createUser(name: string, email: string) {
const httpRequest = http.createHttp()
try {
const response = await httpRequest.request(
"https://api.example.com/users",
{
method: http.RequestMethod.POST,
header: {
"Content-Type": "application/json"
},
extraData: JSON.stringify({
name: name,
email: email
})
}
)
const result = JSON.parse(response.result as string)
return result
} catch (err) {
console.error("创建用户失败:" + JSON.stringify(err))
} finally {
httpRequest.destroy()
}
}
三、封装请求工具类
实际开发中建议封装一个统一的请求工具:
import { http } from "@kit.NetworkKit"
const BASE_URL = "https://api.example.com"
interface RequestConfig {
url: string
method?: http.RequestMethod
data?: object
header?: object
}
async function request(config: RequestConfig): Promise {
const httpRequest = http.createHttp()
try {
const response = await httpRequest.request(
BASE_URL + config.url,
{
method: config.method || http.RequestMethod.GET,
header: {
"Content-Type": "application/json",
...config.header
},
extraData: config.data ? JSON.stringify(config.data) : undefined,
connectTimeout: 15000,
readTimeout: 15000
}
)
if (response.responseCode >= 200 && response.responseCode < 300) {
return JSON.parse(response.result as string) as T
}
throw new Error("HTTP " + response.responseCode)
} finally {
httpRequest.destroy()
}
}
// 使用示例
interface User { id: number; name: string }
let users = await request({ url: "/users" })
let newUser = await request({
url: "/users",
method: http.RequestMethod.POST,
data: { name: "张三", email: "zhangsan@example.com" }
})
四、权限配置
网络请求需要在 module.json5 中声明权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
💡
ohos.permission.INTERNET 属于 system_grant 权限,不需要运行时申请。五、最佳实践
- 每次请求完成后调用
httpRequest.destroy()释放资源 - 设置合理的超时时间,避免长时间等待
- 敏感数据(Token 等)不要硬编码,使用安全存储
- 重要接口添加重试机制
- 使用
try-catch处理所有网络异常