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应用的网络请求代码更简洁、可维护性更强,同时保留了完整的错误处理能力。

相关推荐
御承扬几秒前
鸿蒙NDK UI之文本自定义样式
ui·华为·harmonyos·鸿蒙ndk ui
前端不太难9 分钟前
HarmonyOS 游戏上线前必做的 7 类极端场景测试
游戏·状态模式·harmonyos
大雷神19 分钟前
HarmonyOS智慧农业管理应用开发教程--高高种地--第29篇:数据管理与备份
华为·harmonyos
讯方洋哥1 小时前
HarmonyOS App开发——关系型数据库应用App开发
数据库·harmonyos
巴德鸟2 小时前
华为手机鸿蒙4回退到鸿蒙3到鸿蒙2再回退到EMUI11 最后关闭系统更新
华为·智能手机·harmonyos·降级·升级·回退·emui
一起养小猫2 小时前
Flutter for OpenHarmony 实战_魔方应用UI设计与交互优化
flutter·ui·交互·harmonyos
一只大侠的侠2 小时前
Flutter开源鸿蒙跨平台训练营 Day7Flutter+ArkTS双方案实现轮播图+搜索框+导航组件
flutter·开源·harmonyos
一只大侠的侠3 小时前
Flutter开源鸿蒙跨平台训练营 Day9分类数据的获取与渲染实现
flutter·开源·harmonyos
一只大侠的侠4 小时前
Flutter开源鸿蒙跨平台训练营 Day 5Flutter开发鸿蒙电商应用
flutter·开源·harmonyos
不爱吃糖的程序媛5 小时前
Capacitor:跨平台Web原生应用开发利器,现已全面适配鸿蒙
前端·华为·harmonyos