第二一课:HarmonyOS Next网络请求开发实战

2025-03-06 22:36:52
170次阅读
0个评论

一、HTTP请求实现

1. 权限申请与模块初始化

在HarmonyOS Next中发起HTTP请求需先在module.json5中声明网络权限:

// entry/src/main/module.json5
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "用于加载网络数据",
"usedScene": { "ability": ["EntryAbility"] }
}
]

2. 基础HTTP请求方法

使用@kit.NetworkKit模块发起请求,支持GET/POST等常见方法:

import { http } from '@kit.NetworkKit';
// 创建请求实例
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.log('Response:', data.result);
} else {
console.error('Error:', err.code);
}
}
);

3. 高级封装与拦截器

通过封装NetWorkManage类统一管理请求配置:

class NetWorkManage {
private BASE_URL: string = 'https://api.example.com';

async get(path: string, params?: object) {
try {
const response = await httpRequest.request(
${this.BASE_URL}${path},
{ method: http.RequestMethod.GET, data: params }
);
return response.result;
} catch (error) {
throw new Error(请求失败: ${error.message});
}
}

// 添加请求拦截器
addInterceptor(interceptor: HttpInterceptor) {
httpRequest.on('beforeRequest', interceptor);
}
}

二、WebSocket双向通信

1. WebSocket连接建立

通过WebSocket类实现实时通信:

import { webSocket } from '@kit.NetworkKit';

// 创建WebSocket连接
const ws = new webSocket.WebSocket('wss://echo.websocket.org');

// 监听连接事件
ws.on('open', () => {
console.log('WebSocket连接已建立');
ws.send('Hello Server!');
});

// 接收消息
ws.on('message', (data: string) => {
console.log('收到消息:', data);
});

2. 心跳机制与重连策略

let reconnectAttempts = 0;

// 心跳检测
setInterval(() => {
if (ws.readyState === webSocket.OPEN) {
ws.send('ping');
}
}, 30000);

// 断线重连
ws.on('close', () => {
if (reconnectAttempts < 5) {
setTimeout(() => {
ws.connect();
reconnectAttempts++;
}, 2000);
}
});

三、最佳实践与性能优化

1. 网络请求性能对比

方案 延迟 适用场景 HTTP短连接 50-200ms 低频数据请求 HTTP长连接 30-150ms 高频短数据交互 WebSocket <50ms 实时通信/高频双向数据

2. 关键优化策略实施指南

‌2.1 请求合并方案‌

‌GraphQL实践示例‌ graphql Copy Code query { user(id: "123") { name orders(last: 5) { id amount } } }

合并多个REST API调用为单个请求,减少网络往返次数‌ 需配合后端Schema设计,建议采用分页机制避免超大响应‌ ‌2.3 缓存机制实施‌

‌@ohos.data.preferences应用‌ typescript Copy Code // HarmonyOS示例 import dataPreferences from '@ohos.data.preferences';

// 写入缓存 async function setCache(key: string, value: string) { let prefs = await dataPreferences.getPreferences(this.context, 'mydb'); await prefs.put(key, value); await prefs.flush(); }

// 读取缓存(带过期检查) async function getCache(key: string, ttl: number = 3600) { let prefs = await dataPreferences.getPreferences(this.context, 'mydb'); let value = await prefs.get(key, ''); if (Date.now() - value.timestamp > ttl*1000) return null; return value.data; }

建议采用LRU淘汰策略控制缓存大小‌ 对用户信息、配置参数等低频变更数据效果最佳‌

3. 进阶优化建议

‌协议层优化‌ 升级HTTP/3协议利用QUIC减少队头阻塞‌ 启用TLS1.3缩短握手耗时(相比TLS1.2减少1-RTT)‌ ‌网络质量感知‌

// 网络状态检测示例 const connection = navigator.connection || navigator.mozConnection; if (connection) { console.log(当前网络类型: ${connection.type}, 带宽估算: ${connection.downlink}Mbps); }

收藏00

登录 后评论。没有帐号? 注册 一个。