#鸿蒙通关秘籍#如何确保模块化网络请求封装能够适配多种HTTP方法及文件传输?

HarmonyOS
2024-11-29 15:39:22
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
CI晨光熹

实现一个支持多种HTTP方法及文件传输的模块化封装,可以通过定义一组标准化方法,实现普遍适用的接口。可通过如下步骤:

  1. HttpRequestAbstract中定义常用HTTP方法和文件上传、下载方法,统一接口调用。
  2. 对于文件上传,指定上传路径和配置;对于文件下载,提供下载路径和保存等配置。
  3. 使用RxJS、Promise等进行异步处理,确保操作的可扩展性。

具体代码如下:

export abstract class HttpRequestAbstract {
  constructor(public config: HttpRequestConfig) {
    // Session配置
  }

  request<T = any>(config: HttpRequestConfig): Promise<HttpResponse<T>> {
    // 通用请求实现
  }

  // 定义常用的HTTP方法
  get<T = any>(url: string, config?: HttpRequestConfig): Promise<HttpResponse<T>> {
    return this.request({ ...config, url, method: 'GET' });
  }

  post<T = any>(url: string, data?: Record<string, any>, config?: HttpRequestConfig): Promise<HttpResponse<T>> {
    return this.request({ ...config, url, data, method: 'POST' });
  }

  // 文件上传
  upload<T = any>(url: string, filePath: string, config?: HttpRequestConfig): Promise<HttpResponse<T>> {
    return this.request({ ...config, url, method: 'UPLOAD', filePath });
  }

  // 文件下载
  download<T = any>(url: string, targetPath: string, config?: HttpRequestConfig): Promise<HttpResponse<T>> {
    return this.request({ ...config, url, method: 'DOWNLOAD', filePath: targetPath });
  }
}

// 调用示例
httpClient.upload('/upload', '/path/to/file').then(response => {
  console.log(response);
}).catch(error => {
  console.error('Upload error:', error);
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
分享
微博
QQ
微信
回复
2024-11-29 16:31:49
相关问题
HarmonyOS http网络请求封装的Demo
911浏览 • 1回复 待解决
HarmonyOS工程模块化
714浏览 • 1回复 待解决
HTTP请求传输大于5m文件报错2300023
1281浏览 • 1回复 待解决
HarmonyOS 工程模块化问题
845浏览 • 1回复 待解决
HarmonyOS http请求封装
913浏览 • 1回复 待解决