当前位置: 首页 > article >正文

HarmonyOS NEXT 封装实现好用的网络模块(基于最新5.0的API12)

在 HarmonyOS-NEXT 开发中,网络请求是应用开发中不可或缺的一部分。为了提高开发效率和代码复用性,我们可以封装一个好用的网络模块组件。本文将介绍如何在 HarmonyOS-NEXT 中封装一个功能强大且易于使用的网络模块组件。

封装目的

网络模块使用的频率最高,也是最核心的一个模块。一个好用的网络模块是加快应用开发的神兵利器。虽然官方提供的@ohos.net.http模块很强大,但是官方提供的直接使用不太好使用。

如何让其能像在类似uniapp中的uni.request那般好用?这里介绍下以下封装实现,可以看到使用变得如此简单。同样的模块封装,之前博主已用在自己开发的影视app中啦。

详见:uni-app 影视类小程序开发从零到一 | 开源项目分享_uniapp 开源项目-CSDN博客

uni-app的网络请求库封装及使用(同时支持微信小程序)_uni.request-CSDN博客

这里效仿之前博主在uniapp中的使用经验,特实现以下模块化封装。 

在封装网络模块组件之前,我们需要明确以下需求:

  1. 支持常见的 HTTP 请求方法:如 GET、POST、PUT、DELETE 等。
  2. 支持自定义请求头:允许开发者设置自定义的请求头。
  3. 支持请求拦截器:在请求发送前和响应返回后执行自定义逻辑。
  4. 支持错误处理:能够捕获并处理网络请求中的错误。
  5. 支持 Promise 和 async/await:方便异步操作。

实现步骤

创建网络模块组件

首先,我们创建一个名为 http.ts 的文件,用于封装网络模块组件。

// utils/http.ts

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

class Request {
  private httpClient: http.HttpRequest;
  public baseUrl: string;
  private url: string;
  //private header: Record<string, string>;
  public beforeRequest?: (request: Request) => void;
  public afterRequest?: (response: any) => void;
  private config:http.HttpRequestOptions;


  constructor(options: RequestOptions = {}) {

    this.config = {
      method: options.method || http.RequestMethod.GET,
      header: options.header || {},
      extraData: options.extraData || {}
    };
    this.httpClient =  http.createHttp()
    // 请求的根路径
    this.baseUrl = options.baseUrl || '';
    // 请求的 URL 地址
    this.url = options.url || '';
    // 请求方式,默认为 GET
    this.config.method = options.method || http.RequestMethod.GET;
    // 请求的参数对象
    //this.data = options.data || {};
    // header 请求头
    //this.header = options.header || {};
    this.beforeRequest = options.beforeRequest;
    this.afterRequest = options.afterRequest;
    this.setupInterceptor()
  }

  /**
   * 配置属性拦截器
   */
  setupInterceptor() {
    // 这里可以添加拦截器内容
  }


    // 添加对 header 的支持
  private _mergeHeaders(customHeader: Record<string, string> = {}): Record<string, string> {
    return Object.assign({}, this.config.header, customHeader); // 合并默认 header 和自定义 header
  }

  get(url: string, data: Record<string, any> = {}): Promise<any> {
    this.config.method = http.RequestMethod.GET;
    this.config.extraData = data;
    this.url = this.baseUrl + url;
    return this._();
  }

  post(url: string, data: Record<string, any> = {}, header: Record<string, string> = {}): Promise<any> {
    this.config.method = http.RequestMethod.POST;
    this.config.extraData = data;
    this.config.header = this._mergeHeaders(header); // 合并 header
    this.url = this.baseUrl + url;
    return this._();
  }

  put(url: string, data: Record<string, any> = {}): Promise<any> {
    this.config.method = http.RequestMethod.PUT;
    this.config.extraData = data;
    this.url = this.baseUrl + url;
    return this._();
  }

  delete(url: string, data: Record<string, any> = {}): Promise<any> {
    this.config.method = http.RequestMethod.DELETE;
    this.config.extraData = data;
    this.url = this.baseUrl + url;
    return this._();
  }

  private _(): Promise<any> {
    // 请求之前做一些事
    if (this.beforeRequest && typeof this.beforeRequest === 'function') {
      this.beforeRequest(this);
    }

    // 发起请求
    return new Promise((resolve, reject) => {
      this.httpClient.request(
        this.url,
        this.config,
        (error, data) => {
          if (!error) {
            // 请求之后做一些事
            if (this.afterRequest && typeof this.afterRequest === 'function') {
              this.afterRequest(data.result);
            }
            resolve(data.result);
          } else {
            reject(error)
          }
        }
      );
    });
  }
}

// 定义请求选项的类型
interface RequestOptions extends http.HttpRequestOptions {
  baseUrl?: string;
  url?: string;
  beforeRequest?: (request: Request) => void;
  afterRequest?: (response: any) => void;
}

export const $http = new Request();

添加请求拦截器

为了进一步增强网络模块组件的功能,我们可以根据需要修改并添加请求拦截器,在请求发送前和响应返回后执行自定义逻辑。该步骤非必须,根据个人需要。

配置权限

为了在 HarmonyOS 应用中使用网络请求,还需要在 config.json 文件中申请 ohos.permission.INTERNET 权限。

如何使用

有了以上封装,使用就变得很简单啦,举例如下:

import { $http } from '../../utils/http';

interface Result{
  data:string;
}

$http.baseUrl = "http://175.178.126.10:8000"

@Entry
@Component
struct Index {
  @State message: string = 'Hello World1';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)

        Button('test1').width(300).margin({ top: 20 })
          .onClick(() => {
            // 需要执行的操作
            const url ="/api/v1/swiperlist";

            $http.get(url).then((result: Result)  => {
              console.log('result:', result);
            }).catch((error:Error) => {
              console.error('Error:', error);
              this.message = 'Request failed!';
            });
          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

其他资源

文档中心

uni-app的网络请求库封装及使用(同时支持微信小程序)_uni.request-CSDN博客

https://juejin.cn/post/7388470580465434676

Client Initialization | Socket.IO

uni-app的网络请求库封装及使用(同时支持微信小程序)_uni.request-CSDN博客

【鸿蒙HarmonyOS】网络请求http代码实现_鸿蒙axios 获取response header 中的token-CSDN博客

HarmonyOS NEXT开发实战:网络请求库-http_鸿蒙如何封装统一的接口请求配置-CSDN博客


http://www.kler.cn/news/306571.html

相关文章:

  • Android 12 Launcher3 去掉Hotseat
  • JVM 调优篇7 调优案例3- gc overhead limit exceed
  • ListBox显示最新数据、左移和右移操作
  • K8s中HPA自动扩缩容及hml
  • idea2024.2永久使用
  • MFC工控项目实例之十五定时刷新PC6325A模拟量输入
  • HTML添加文字
  • 【深度学习】Pytorch基础
  • 分享一些成功的 SQL 优化案例
  • 2024工业机器视觉产业现状
  • 多模态大语言模型综述(中)-算法实用指南
  • 如何在Django中创建新的模型实例
  • MFC工控项目实例之十六输入信号验证
  • app抓包 chrome://inspect/#devices
  • 2024.9.12(k8s环境搭建2)
  • WebSocket vs. Server-Sent Events:选择最适合你的实时数据流技术
  • VUE3中ref与reactive
  • Sentinel 安装
  • BSV区块链上的覆盖网络服务现已开放公测
  • 常回家看看之house_of_cat
  • 基于单片机的超声波液位检测系统(论文+源码)
  • STM32 HAL freertos零基础(二)-通过STM32CubeMX配置Freertos后在程序中进行任务创建,便于任务管理与识别。
  • 微服务保护之熔断降级
  • 【前端】ref引用的作用
  • 2----手机维修工具 集合解锁 修复参数 刷机支持高通 MTK 展讯等芯片 支持一些PDA设备
  • 【机器学习】--- 生成对抗网络 (GANs)
  • Linux-Swap分区使用与扩容
  • Java集合接口List
  • C Primer Plus 第5章习题
  • 【从问题中去学习k8s】k8s中的常见面试题(夯实理论基础)(三十一)