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

相关推荐
梦想不只是梦与想4 小时前
鸿蒙 测试工具:DevEco Testing(一)
测试工具·harmonyos·testing
大锅盖17 小时前
Web 工单要调用相机,第一步不是打开取景框,而是建立能力门禁
前端·数码相机·harmonyos
贾伟康11 小时前
【华夏二十四节气|07】HarmonyOS 6.0.2(22) ArkTS 节气搜索实战:多字段匹配与四态闭环
移动开发·harmonyos·arkts·arkui·本地搜索
大龄秃头程序员12 小时前
Flutter 项目鸿蒙适配实战:从环境搭建到多环境打包全指南
harmonyos
贾伟康13 小时前
【万能转换器|18】HarmonyOS ArkTS 权限与隐私实战:让 module.json5、功能说明和拒绝路径一致
移动开发·harmonyos·arkts·权限管理·隐私合规
贾伟康13 小时前
【万能转换器|19】HarmonyOS ArkTS 回归测试实战:覆盖启动、空数据、异常输入和重复点击
软件测试·移动开发·harmonyos·arkts·回归测试
UnicornIT15 小时前
【HarmonyOS】时间管理类APP:做成“自适应“
ui·华为·harmonyos·鸿蒙
less_1213815 小时前
HarmonyOS WPS Open SDK:不落地、水印与功能开关的合规打开策略
华为·harmonyos·wps
贾伟康16 小时前
【万能转换器|20】HarmonyOS ArkTS AppGallery 发布复查实战:核对包名、版本、设备、素材和离线声明
移动开发·harmonyos·arkts·appgallery·应用发布
OH_TPC1 天前
HarmonyOS APP开发---“滤镜大师“图像处理App,需要用到这个库
java·图像处理·华为·harmonyos·鸿蒙