在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组件...
  }
}
        关键实现说明:
- 
Promise封装:
- 将回调式API转换为Promise风格
 - 统一处理成功/失败状态
 
 - 
资源管理:
- 使用
destroy()确保释放HTTP资源 - 避免内存泄漏
 
 - 使用
 - 
错误处理:
- 网络错误(4xx/5xx状态码)
 - JSON解析错误
 - 系统级错误(如无网络)
 
 - 
类型安全:
- 使用TypeScript类型约束
 - 自动处理JSON序列化
 
 - 
配置灵活性:
- 支持自定义请求头
 - 自动设置Content-Type
 - 支持GET/POST/PUT/DELETE方法
 
 
添加网络权限:
在module.json5中添加权限:
            
            
              json
              
              
            
          
          {
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}
        最佳实践建议:
- 添加超时控制:
 
            
            
              arduino
              
              
            
          
          // 在request配置中添加
httpRequest.request(config.url, {
  connectTimeout: 30000, // 30秒超时
  // ...其他配置
});
        - 添加重试机制:
 
            
            
              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;
  }
}
        - 添加请求拦截器:
 
            
            
              ini
              
              
            
          
          // 全局请求拦截示例
const originalRequest = httpRequest;
httpRequest = async (config) => {
  // 添加全局token
  config.header = {
    ...config.header,
    'Authorization': `Bearer ${getGlobalToken()}`
  };
  return originalRequest(config);
};
        此封装方案提供了现代化的异步请求处理方式,使HarmonyOS 5.0应用的网络请求代码更简洁、可维护性更强,同时保留了完整的错误处理能力。