您的位置:首页 > 财经 > 产业 > HarmonyOS NEXT 封装实现好用的网络模块(基于最新5.0的API12)

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

2024/10/7 2:31:25 来源:https://blog.csdn.net/qq8864/article/details/142152020  浏览:    关键词: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.tsimport 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 || '';// 请求方式,默认为 GETthis.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); // 合并 headerthis.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博客

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com