鸿蒙开发中HTTP网络请求
HTTP请求开发指南摘要 本文对比了原生HTTP模块(@ohos.net.http)与第三方Axios的特点,详细解析了GET/POST/PUT/PATCH/DELETE等请求方法的语义与实现,包含参数设置、响应处理及销毁流程。特别说明文件上传、HTTPS证书校验等高级功能,并给出拦截器封装、性能优化(连接复用/数据压缩)等实用方案。针对不同场景推荐:基础请求用原生模块,复杂业务用Axios,实时
·
本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、HTTP核心模块对比
模块 | 特点 | 适用场景 |
---|---|---|
.net.http |
系统原生API,支持HTTP/HTTPS | 常规请求、文件上传下载 |
.axios |
第三方库(需安装),Promise风格 | 需要拦截器、复杂封装场景 |
WebSocket |
双向实时通信 | 聊天室、实时数据推送 |
二、基础HTTP请求
方法 | 语义 | 典型应用场景 | 是否携带Body |
---|---|---|---|
GET | 获取资源 | 查询数据、获取列表 | ❌ 否 |
POST | 创建资源 | 提交表单、新增数据 | ✅ 是 |
PUT | 完整更新资源 | 替换整个文档/对象 | ✅ 是 |
PATCH | 部分更新资源 | 修改个别字段 | ✅ 是 |
DELETE | 删除资源 | 移除数据记录 | ❌ 可选 |
HEAD | 获取响应头(无Body) | 检查资源是否存在/变更 | ❌ 否 |
OPTIONS | 查询服务器支持的方法 | 跨域预检请求(CORS) | ❌ 否 |
1. GET请求示例
import http from '@ohos.net.http';
async function fetchData() {
// 1. 创建请求对象
let httpRequest = http.createHttp();
// 2. 设置请求参数
let url = 'https://api.example.com/data?id=123';
let header = { 'Content-Type': 'application/json' };
// 3. 发起请求
try {
let response = await httpRequest.request(
url,
{ method: 'GET', header }
);
// 4. 处理响应
if (response.responseCode === 200) {
console.log(JSON.parse(response.result));
}
} catch (err) {
console.error(`请求失败: ${err.code}`);
} finally {
// 5. 销毁请求
httpRequest.destroy();
}
}
2. POST请求(带Body)
let options = {
method: 'POST',
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify({ title: 'foo', body: 'bar' })
};
httpRequest.request(url, options, (err, data) => {
if (!err) {
console.log("响应状态码:", data.responseCode);
}
});
3. PUT请求
import http from '@ohos.net.http';
async function updateUser(userId: string, userData: object) {
let httpRequest = http.createHttp();
try {
let response = await httpRequest.request(
`https://api.example.com/users/${userId}`,
{
method: 'PUT', // 关键设置
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify(userData) // 完整用户数据
}
);
console.log('更新结果:', response.result);
} finally {
httpRequest.destroy();
}
}
// 调用示例
updateUser('123', { name: '张三', age: 30 });
4. PATCH 请求
async function updateUserName(userId: string, newName: string) {
let httpRequest = http.createHttp();
try {
await httpRequest.request(
`https://api.example.com/users/${userId}/name`,
{
method: 'PATCH', // 关键设置
header: { 'Content-Type': 'application/json-patch+json' },
extraData: JSON.stringify([{ "op": "replace", "path": "/name", "value": newName }])
}
);
} finally {
httpRequest.destroy();
}
}
5. DELETE 请求
async function deletePost(postId: string) {
let httpRequest = http.createHttp();
try {
let response = await httpRequest.request(
`https://api.example.com/posts/${postId}`,
{ method: 'DELETE' } // 关键设置
);
if (response.responseCode === 204) {
console.log('删除成功');
}
} finally {
httpRequest.destroy();
}
}
三、高级功能实现
1. 文件上传(Multipart)
import fileio from '@ohos.fileio';
async function uploadFile(filePath: string) {
let fileStat = fileio.statSync(filePath);
let file = fileio.openSync(filePath, 0o100); // 只读模式
let options = {
method: 'POST',
files: [
{
filename: 'image.jpg',
name: 'file',
uri: `internal://app/${filePath}`,
type: 'image/jpeg',
size: fileStat.size
}
]
};
httpRequest.upload(url, options, (progress) => {
console.log(`上传进度: ${progress.percent}%`);
});
}
2. 请求拦截器(Axios风格)
// 安装axios:ohpm install @ohos/axios
import axios from '@ohos/axios';
// 请求拦截
axios.interceptors.request.use(config => {
config.header['X-Token'] = getToken();
return config;
});
// 响应拦截
axios.interceptors.response.use(
response => {
if (response.status !== 200) {
throw new Error('服务异常');
}
return response.data;
},
error => {
showToast('网络错误');
return Promise.reject(error);
}
);
四、安全与优化
1. HTTPS证书校验
let sslOptions = {
protocols: [http.Protocol.TLSv12],
useCipherSuites: [
'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384'
],
ca: '/path/to/cert.pem' // 自定义CA证书
};
httpRequest.request(url, {
method: 'GET',
sslOptions
});
2. 请求缓存策略
let cacheOptions = {
priority: http.HttpCachePriority.LOW,
readBehavior: http.HttpCacheReadBehavior.ONLINE
};
httpRequest.request(url, {
method: 'GET',
cacheOptions
});
五、实战案例:封装HTTP工具类
export class HttpUtil {
private static instance: HttpUtil;
private httpRequest: http.HttpRequest;
private constructor() {
this.httpRequest = http.createHttp();
}
static getInstance(): HttpUtil {
if (!HttpUtil.instance) {
HttpUtil.instance = new HttpUtil();
}
return HttpUtil.instance;
}
async get(url: string, params?: Record<string, string>) {
let query = params ? '?' + new URLSearchParams(params).toString() : '';
return this.request('GET', url + query);
}
private async request(method: string, url: string, data?: any) {
try {
let response = await this.httpRequest.request(url, {
method,
header: { 'Content-Type': 'application/json' },
extraData: data ? JSON.stringify(data) : undefined
});
return JSON.parse(response.result);
} catch (err) {
throw new Error(`HTTP Error: ${err.code}`);
}
}
destroy() {
this.httpRequest.destroy();
}
}
// 使用示例
HttpUtil.getInstance().get('https://api.example.com/data', { page: 1 });
六、调试与问题排查
1. 网络状态监听
import network from '@ohos.net.network';
network.on('netAvailable', (data) => {
console.log(`当前网络类型: ${data.netInfo.type}`);
});
2. 常见错误码处理
错误码 | 含义 | 解决方案 |
---|---|---|
200 | 成功 | 正常处理响应数据 |
401 | 未授权 | 检查Token或重新登录 |
404 | 资源不存在 | 验证URL是否正确 |
500 | 服务器内部错误 | 联系后端排查 |
七、性能优化建议
-
连接复用
// 全局保持单例HttpRequest const httpRequest = http.createHttp();
-
数据压缩
let headers = { 'Accept-Encoding': 'gzip, deflate' };
-
分页加载
async function loadPage(page: number) { return httpRequest.get(url, { page, size: 20 }); }
总结对比
方案 | 优势 | 推荐场景 |
---|---|---|
原生HTTP模块 | 零依赖、系统级优化 | 基础请求、文件操作 |
Axios封装 | 拦截器、Promise链式调用 | 复杂业务逻辑 |
WebSocket | 全双工通信 | 实时性要求高的场景 |
推荐内容
点击阅读全文
更多推荐
活动日历
查看更多
活动时间 2024-06-24 00:00:00

鸿蒙OS初体验:从0到1的开发者之路·苏州
活动时间 2024-06-11 00:00:00

鸿蒙OS初体验:从0到1的开发者之路·武汉
活动时间 2024-06-11 00:00:00

鸿蒙OS初体验:从0到1的开发者之路·长沙
活动时间 2024-06-11 00:00:00

鸿蒙OS初体验:从0到1的开发者之路·西安
活动时间 2024-06-11 00:00:00

鸿蒙OS初体验:从0到1的开发者之路·南京
社区排行榜
所有评论(0)