展示如何在HarmonyOS应用中进行网络请求,包括GET、POST、文件上传等
API级别: API 9+ | 项目路径: HarmonyOS_NEXT/Connectivity/Http
HTTP示例展示了网络请求的基本用法,包括请求参数配置、响应处理、错误处理等。
import http from '@ohos.http';
let httpRequest = http.createHttp();
async get(url: string): Promise {
try {
let response = await httpRequest.request(
url,
{
method: http.RequestMethod.GET,
header: { 'Accept': 'application/json' },
connectTimeout: 30000,
readTimeout: 30000
}
);
if (response.responseCode === 200) {
return JSON.parse(response.result as string);
}
} finally {
httpRequest.destroy(); // 必须释放资源
}
}
async post(url: string, data: object): Promise {
let httpRequest = http.createHttp();
try {
let response = await httpRequest.request(
url,
{
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify(data)
}
);
return JSON.parse(response.result as string);
} finally {
httpRequest.destroy();
}
}
| 方法 | 说明 |
|---|---|
| GET | 获取数据 |
| POST | 提交数据 |
| PUT | 更新数据 |
| DELETE | 删除数据 |
| HEAD | 获取头部 |
| PATCH | 部分更新 |
| 响应码 | 说明 | 处理方式 |
|---|---|---|
| 200 | 成功 | 解析响应数据 |
| 201 | 创建成功 | 返回新资源 |
| 400 | 请求错误 | 检查请求参数 |
| 401 | 未授权 | 跳转登录 |
| 404 | 资源不存在 | 提示用户 |
| 500 | 服务器错误 | 提示重试 |
• 必须在finally中调用destroy()释放资源
• 合理设置connectTimeout和readTimeout
• 需要在module.json5中配置INTERNET权限
• 建议做好错误处理和重试机制
📎 官方仓库链接