鸿蒙Next中http.createhttp()如何进行封装

在鸿蒙Next开发中,使用http.createhttp()进行网络请求时,如何进行合理的封装?希望能提供一个简洁高效的封装方案,包括错误处理、请求拦截和响应解析等常见功能,最好能有代码示例说明。

2 回复

鸿蒙Next里封装http.createHttp()?简单!先搞个HttpManager类,把请求方法包进去,加个超时和重试机制,错误统一处理。再写个request()方法,支持GET/POST,返回Promise。最后加个拦截器,打印日志。搞定!代码优雅,老板直呼内行!

更多关于鸿蒙Next中http.createhttp()如何进行封装的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next中,可以通过封装http.createHttp()来简化网络请求操作,提高代码复用性。以下是一个基本的封装示例:

import http from '@ohos.net.http';

class HttpUtil {
  private httpRequest: http.HttpRequest;

  constructor() {
    this.httpRequest = http.createHttp();
  }

  // GET请求封装
  async get(url: string, params?: Record<string, string>): Promise<any> {
    try {
      let fullUrl = url;
      if (params) {
        const queryParams = new URLSearchParams(params).toString();
        fullUrl += `?${queryParams}`;
      }

      const options = {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        }
      };

      const response = await this.httpRequest.request(fullUrl, options);
      return JSON.parse(response.result as string);
    } catch (error) {
      console.error('GET请求失败:', error);
      throw error;
    }
  }

  // POST请求封装
  async post(url: string, data: Record<string, any>): Promise<any> {
    try {
      const options = {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json'
        },
        extraData: JSON.stringify(data)
      };

      const response = await this.httpRequest.request(url, options);
      return JSON.parse(response.result as string);
    } catch (error) {
      console.error('POST请求失败:', error);
      throw error;
    }
  }

  // 销毁HTTP实例
  destroy() {
    this.httpRequest.destroy();
  }
}

// 使用示例
const httpUtil = new HttpUtil();

// GET请求
const userData = await httpUtil.get('https://api.example.com/users', { id: '123' });

// POST请求
const result = await httpUtil.post('https://api.example.com/login', {
  username: 'admin',
  password: '123456'
});

封装要点:

  1. 创建HttpUtil类管理HTTP实例
  2. 封装GET/POST等常用方法
  3. 统一处理请求参数和响应数据
  4. 添加错误处理
  5. 提供销毁方法释放资源

扩展建议:

  • 添加请求拦截器
  • 实现文件上传下载
  • 添加超时配置
  • 支持更多HTTP方法
  • 添加缓存机制

这样的封装使网络请求更简洁,便于维护和统一管理。

回到顶部