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

87 阅读1分钟

一、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. 关键优化策略

‌数据压缩‌:对请求体启用GZIP压缩减少传输量‌
‌请求合并‌:使用GraphQL合并多个API调用‌
‌缓存机制‌:通过@ohos.data.preferences缓存高频数据‌