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 的文件,用于封装网络模块组件。

TypeScript 复制代码
// 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 权限。

如何使用

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

TypeScript 复制代码
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博客

相关推荐
不悔哥17 分钟前
openwrt wsdd模块介绍
linux·c语言·网络·tcp/ip·智能路由器
SUGERBOOM23 分钟前
华为eNSP使用详解
网络·华为
洁洁!1 小时前
【计算机网络】数据链路层深度解析
网络·网络协议·计算机网络
Aomnitrix3 小时前
网络协议全景:Linux环境下的TCP/IP、UDP
linux·运维·网络·c++·网络协议·tcp/ip·运维开发
哲伦贼稳妥3 小时前
网络运维故障处理
运维·网络·经验分享·职场和发展
bite_joker_xue3 小时前
HCIA--实验十六:ACL通信实验(2)
网络
物联网菜鸟3 小时前
linux网络编程1
网络
无衣同学9 小时前
HCIP--<OSPF2>
网络
awonw10 小时前
[网络][CISCO]CISCO IOS升级
网络·ios
snow@li11 小时前
AI问答-HTTP:理解 Content-Disposition
网络·网络协议·http