HarmonyOS 5.0,使用Promise异步回调方式封装http请求

在HarmonyOS 5.0中,我们可以使用@ohos.net.http模块封装基于Promise的HTTP请求。以下是完整实现方案:

1. 创建Promise封装工具 (httpUtil.ts)

typescript 复制代码
import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';

// 定义请求配置类型
type RequestConfig = {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  header?: Object;
  body?: string | Object;
};

// 封装HTTP请求
export function httpRequest(config: RequestConfig): Promise<any> {
  return new Promise((resolve, reject) => {
    // 1. 创建HTTP客户端
    const httpRequest = http.createHttp();

    // 2. 处理请求体(对象转JSON字符串)
    let requestBody = config.body;
    if (typeof config.body === 'object') {
      requestBody = JSON.stringify(config.body);
      config.header = {
        ...config.header,
        'Content-Type': 'application/json'
      };
    }

    // 3. 发送请求
    httpRequest.request(
      config.url,
      {
        method: config.method || 'GET',
        header: config.header || {},
        extraData: requestBody
      },
      (err: BusinessError, response: http.HttpResponse) => {
        // 4. 处理响应
        if (err) {
          httpRequest.destroy(); // 释放资源
          reject(new Error(`Network error: ${err.code} - ${err.message}`));
          return;
        }

        // 5. 检查状态码
        if (response.responseCode >= 200 && response.responseCode < 300) {
          try {
            // 6. 尝试解析JSON
            if (typeof response.result === 'string') {
              resolve(JSON.parse(response.result));
            } else {
              resolve(response.result);
            }
          } catch (e) {
            resolve(response.result); // 返回原始数据
          }
        } else {
          reject(new Error(`HTTP ${response.responseCode}: ${response.responseMessage}`));
        }

        // 7. 释放资源
        httpRequest.destroy();
      }
    );
  });
}

// 快捷方法
export const httpGet = (url: string, header?: Object) => 
  httpRequest({ url, method: 'GET', header });

export const httpPost = (url: string, body: Object | string, header?: Object) => 
  httpRequest({ url, method: 'POST', body, header });

2. 在业务中使用 (示例)

typescript 复制代码
// 导入封装工具
import { httpGet, httpPost } from './httpUtil';

// GET请求示例
async function fetchUserData() {
  try {
    const API_URL = 'https://api.example.com/users';
    
    const response = await httpGet(API_URL, {
      'Authorization': 'Bearer your_token_here'
    });
    
    console.log('用户数据:', response);
    return response;
  } catch (error) {
    console.error('请求失败:', error.message);
    // 处理错误
  }
}

// POST请求示例
async function createNewUser(userData: object) {
  try {
    const API_URL = 'https://api.example.com/users';
    
    const result = await httpPost(API_URL, userData, {
      'X-Custom-Header': 'value'
    });
    
    console.log('创建成功:', result);
    return result;
  } catch (error) {
    console.error('创建失败:', error.message);
    // 处理错误
  }
}

// 在界面中调用
@Entry
@Component
struct UserPage {
  async aboutToAppear() {
    const users = await fetchUserData();
    // 更新UI...
  }
  
  build() {
    // UI组件...
  }
}

关键实现说明:

  1. Promise封装

    • 将回调式API转换为Promise风格
    • 统一处理成功/失败状态
  2. 资源管理

    • 使用destroy()确保释放HTTP资源
    • 避免内存泄漏
  3. 错误处理

    • 网络错误(4xx/5xx状态码)
    • JSON解析错误
    • 系统级错误(如无网络)
  4. 类型安全

    • 使用TypeScript类型约束
    • 自动处理JSON序列化
  5. 配置灵活性

    • 支持自定义请求头
    • 自动设置Content-Type
    • 支持GET/POST/PUT/DELETE方法

添加网络权限:

module.json5中添加权限:

json 复制代码
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

最佳实践建议:

  1. 添加超时控制
arduino 复制代码
// 在request配置中添加
httpRequest.request(config.url, {
  connectTimeout: 30000, // 30秒超时
  // ...其他配置
});
  1. 添加重试机制
javascript 复制代码
async function requestWithRetry(config: RequestConfig, retries = 3) {
  try {
    return await httpRequest(config);
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      return requestWithRetry(config, retries - 1);
    }
    throw error;
  }
}
  1. 添加请求拦截器
ini 复制代码
// 全局请求拦截示例
const originalRequest = httpRequest;
httpRequest = async (config) => {
  // 添加全局token
  config.header = {
    ...config.header,
    'Authorization': `Bearer ${getGlobalToken()}`
  };
  return originalRequest(config);
};

此封装方案提供了现代化的异步请求处理方式,使HarmonyOS 5.0应用的网络请求代码更简洁、可维护性更强,同时保留了完整的错误处理能力。

相关推荐
zhanshuo11 小时前
如何用 ArkTS 实现丝滑又安全的表单输入验证?一篇文章讲清楚!
harmonyos
zhanshuo11 小时前
掌握 ArkTS 复杂数据绑定:从双向输入到多组件状态同步
harmonyos
SuperHeroWu712 小时前
【HarmonyOS】鸿蒙应用开发中常用的三方库介绍和使用示例
华为·harmonyos
jz_ddk12 小时前
[HarmonyOS] 鸿蒙LiteOS-A内核深度解析 —— 面向 IoT 与智能终端的“小而强大”内核
物联网·学习·华为·harmonyos
liuhaikang17 小时前
【鸿蒙HarmonyOS Next App实战开发】视频提取音频
华为·音视频·harmonyos
爱笑的眼睛1117 小时前
HarmonyOS应用上架流程详解
华为·harmonyos
zhanshuo2 天前
构建可扩展的状态系统:基于 ArkTS 的模块化状态管理设计与实现
harmonyos
zhanshuo2 天前
ArkTS 模块通信全解析:用事件总线实现页面消息联动
harmonyos
codefish7982 天前
鸿蒙开发学习之路:从入门到实践的全面指南
harmonyos
yrjw2 天前
一款基于react-native harmonyOS 封装的【文档】文件预览查看开源库(基于Harmony 原生文件预览服务进行封装)
harmonyos