HarmonyOS NEXT应用开发(一、打造最好用的网络通信模块组件)

news/2024/10/9 15:04:26/

随着HarmonyOS NEXT 的发布,越来越多的开发者开始关注如何在这个新平台上高效地进行应用开发。其中网络通信模块的封装尤为关键。纵观HarmonyOS的众多三方网络库及封装,竟没有一个简单好用的。虽然有个axios的鸿蒙版,但有点儿重了也不是很好用。本篇博文将介绍如何将uniapp中的luch-request网络库移植到HarmonyOS中,从而实现更简单、高效的HTTP网络通信。

为什么选择luch-request?

在HarmonyOS中,原始的ohos.net.http接口虽然功能强大,但在实际使用中却存在一些复杂性和局限性。这使得开发者在进行网络请求时需要写更多的代码,而且处理错误、配置请求等操作也较为繁琐。而uniapp中的luch-request,使用起来特别的简单好用,且比axios更简单和轻量级,功能一点也不弱。

相较而言,luch-request网络库的优点:

  1. 简洁易用:提供了易于理解的API接口,开发者可以通过简单的调用来实现复杂的网络请求。
  2. Promise支持:内置了Promise支持,方便与异步编程结合,提升代码的可读性和维护性。
  3. 请求拦截器和响应拦截器:可以方便地添加请求和响应的拦截器,用于统一处理请求头、参数和错误处理。
  4. 自动化的JSON数据解析:返回的数据会自动解析成JSON格式,省去了手动解析的步骤。
  5. 支持多种请求方式:GET、POST、PUT、DELETE等多种请求方式都能轻松实现。

luch-request网络库地址:GitHub - lei-mu/luch-request: luch-request 是一个基于Promise 开发的uni-app跨平台、项目级别的请求库,它有更小的体积,易用的api,方便简单的自定义能力。

官网介绍: 

luch-request

移植步骤

下面,我们将详细介绍如何将unIapp平台下的luch-request网络库移植到HarmonyOS中。

步骤一:准备环境

首先,你需要在HarmonyOS项目中引入luch-request库。我已经移植好了,发布在了Openharmony的三方库中。

移植后的gitee地址:yyz116/h_request

发布到三库库的地址:OpenHarmony三方库中心仓 

注:当前该三方库1.0.1版本正在审核中。可以从gitee项目中下载源码体验,内涵单元测试及demo。

可以这样引入使用:

ohpm  install @yyz116/h_requestimport Request, { HttpRequestConfig, HttpResponse } from '@yyz116/h_request'

步骤二:封装请求模块

在你的HarmonyOS项目中创建一个新的网络请求模块,例如request.js,并在其中引入luch-request库。你需要对库进行小幅修改,以确保其与HarmonyOS环境兼容。

import Request, { HttpRequestConfig, HttpResponse } from '@yyz116/h_request'const httpRequest = new Request();httpRequest.setConfig((config) => {// Set base configconfig.baseURL = "https://your.api.url"; // 替换为你的API地址return config;
});httpRequest.interceptors.request.use((config) => {// 可以在这里添加请求拦截器return config;
}, (error) => {return Promise.reject(error);
});httpRequest.interceptors.response.use((response) => {// 可以在这里添加响应拦截器return response.data;
}, (error) => {return Promise.reject(error);
});export default httpRequest;

步骤三:使用网络请求模块

在你的应用中,你可以通过引入request.js来进行网络请求。

import httpRequest from './request';// 示例 GET 请求
httpRequest.get('/endpoint').then(data => {console.log("获取数据成功:", data);}).catch(error => {console.error("请求失败:", error);});// 示例 POST 请求
httpRequest.post('/endpoint', { key: 'value' }).then(data => {console.log("数据提交成功:", data);}).catch(error => {console.error("请求失败:", error);});

使用举例

// 发送post请求
http.post('api/v1/soonmovie', {start:0,count:1}).then((res:HttpResponse<Result>) => {hilog.debug(0x0000,"request",res.data.message)hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)}).catch((err:HttpResponse<Error>) => {hilog.debug(0x0000,"request","err.data.code:%d",err.data.code)hilog.debug(0x0000,"request",err.data.message)});// 发送get请求,带参数
http.get('api/v1/musicsearchlrc', {params:{id:"543656129",kind:"wy"}}).then((res:HttpResponse<Result>) => {hilog.debug(0x0000,"request",res.data.message)hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)}).catch((err:HttpResponse<Error>) => {hilog.debug(0x0000,"request","err.data.code:%d",err.data.code)hilog.debug(0x0000,"request",err.data.message)});})

可以看到,接口使用变得如此简单。 且可以增加拦截器(建议把拦截器封装到单独的一个模块文件里,以下示例仅为示例utils/request.js):

 export const setRequestConfig = () => {http.setConfig((config:HttpRequestConfig) => {config.baseURL = "http://175.178.126.10:8000/";return config;});// 请求拦截http.interceptors.request.use((config) => {hilog.debug(0x0000,"request",'请求拦截')return config},(error) => {return Promise.reject(error)})// 响应拦截http.interceptors.response.use((response:HttpResponse) => {hilog.debug(0x0000,"request",'响应拦截')if (response.data.code == 401) {// 提示重新登录console.log('请登录')setTimeout(() => {console.log('请请登录')}, 1000);}return response},(error) => {return Promise.reject(error)})}

接口使用变得清晰明了,如下api封装模块user.js: 

import { setRequestConfig } from '@/utils/request.js';// 调用setRequestConfig函数进行请求配置
setRequestConfig();
const http = uni.$u.http
// 发起登录请求
export const requestLogin = (data) => http.post('/wx-api/login', data);
//请求验证码  /wx-api/validcode   get   参数:{"phone":"xxx"}
export const  requestVerificationCode = (params = {}) => http.get(`/wx-api/validcode`, params)
//发起注册请求   /wx-api/register   post   
/*
参数:{"code": "xxx","phone": "xxx","verifyCode": "xxx","nickname": "xxx","avatarUrl": "xxx","gender":"0"}
*/
export const requestRegister = (data)=>http.post('/wx-api/register',data)
//获取个人中心信息   /wx-api/me/info   get
export const requestUserInfo = () => http.get('/wx-api/me/info')
//修改个人昵称  /wx-api/update/nickname post  参数:newNickname
export const requestNickname = (data)=>http.post('/wx-api/update/nickname',data)

完整示例

import Request, { HttpRequestConfig, HttpResponse } from '@yyz116/h_request'
import { hilog } from '@kit.PerformanceAnalysisKit';interface Movie{id:string;cover:string;title:string;gener:string;rate:number;
}
interface Result{code:number;message:string;data:Array<Movie>;count:number;start:number;total:number;title:string;}
interface Error{code:number;message:string;data:Array<Movie>;count:number;start:number;total:number;title:string;
}@Entry
@Component
struct Index {@State message: string = 'Hello World';build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Button('test1').width(300).margin({ top: 20 }).onClick(() => {// 需要执行的操作const http = new Request();http.setConfig((config:HttpRequestConfig) => {config.baseURL = "http://175.178.126.10:8000/";return config;});// 请求拦截http.interceptors.request.use((config) => {hilog.debug(0x0000,"request",'请求拦截')return config},(error) => {return Promise.reject(error)})// 响应拦截http.interceptors.response.use((response:HttpResponse) => {hilog.debug(0x0000,"request",'响应拦截')if (response.data.code == 401) {// 提示重新登录console.log('请登录')setTimeout(() => {console.log('请请登录')}, 1000);}return response},(error) => {return Promise.reject(error)})http.post('api/v1/soonmovie', {start:0,count:1}).then((res:HttpResponse<Result>) => {hilog.debug(0x0000,"request",res.data.message)hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)}).catch((err:HttpResponse<Error>) => {hilog.debug(0x0000,"request","err.data.code:%d",err.data.code)hilog.debug(0x0000,"request",err.data.message)});http.get('api/v1/musicsearchlrc', {params:{id:"543656129",kind:"wy"}}).then((res:HttpResponse<Result>) => {hilog.debug(0x0000,"request",res.data.message)hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)}).catch((err:HttpResponse<Error>) => {hilog.debug(0x0000,"request","err.data.code:%d",err.data.code)hilog.debug(0x0000,"request",err.data.message)});})}.width('100%')}.height('100%')}
}

总结

通过将luch-request网络库移植到HarmonyOS,我们大大简化了网络请求的过程。开发者可以享受到更加清晰、简洁的API,同时也提升了开发效率。如果你正在开发HarmonyOS应用,不妨尝试一下这个网络通信模块封装,让你的开发过程更加顺畅。希望本文对你有所帮助,欢迎交流与分享经验!

写在最后

最后,推荐下笔者的业余开源app影视项目“爱影家”,推荐分享给与我一样喜欢观影的朋友。

开源地址:爱影家app开源项目介绍及源码

https://gitee.com/yyz116/imovie

其他资源

luch-request

yyz116/h_request

OpenAtom OpenHarmony


http://www.ppmy.cn/news/1536696.html

相关文章

初识Linux · 自主Shell编写

目录 前言&#xff1a; 1 命令行解释器部分 2 获取用户命令行参数 3 命令行参数进行分割 4 执行命令 5 判断命令是否为内建命令 前言&#xff1a; 本文介绍是自主Shell编写&#xff0c;对于shell&#xff0c;即外壳解释程序&#xff0c;我们目前接触到的命令行解释器&am…

【网络安全 | 渗透工具】自动化 .env/.git文件检测

原创文章,禁止转载。 文章目录 1. 安装 DotGit2. 配置 DotGit3. 使用 DotGit 检测 .env / .git 文件1. 安装 DotGit 在谷歌应用商店中搜索 DotGit 并进行安装: 2. 配置 DotGit 安装完成后,可以在设置中开启或关闭相关功能: 3. 使用 DotGit 检测 .env / .git 文件 接下来…

【深度学习】—激活函数、ReLU 函数、 Sigmoid 函数、Tanh 函数

【深度学习】—激活函数、ReLU 函数、 Sigmoid 函数、Tanh 函数 4.1.2 激活函数ReLU 函数参数化 ReLU Sigmoid 函数背景绘制 sigmoid 函数Sigmoid 函数的导数 Tanh 函数Tanh 函数的导数总结 4.1.2 激活函数 激活函数&#xff08;activation function&#xff09;用于计算加权和…

通过MySQL Workbench 将 SQL Server 迁移到GreatSQL

通过MySQL Workbench 将 SQL Server 迁移到GreatSQL 一、概述 MySQL Workbench 提供了可以将Microsoft SQL Server的表结构和数据迁移到 GreatSQL 的功能&#xff0c;此次将通过MySQL Workbench将SQL Server的数据迁移到GreatSQL。 本文章只是简单演示一下单张表的迁移&…

滚雪球学Oracle[3.2讲]:查询与数据操作基础

全文目录&#xff1a; 前言一、复杂查询的优化&#xff1a;索引与查询重写1.1 使用索引优化查询索引的原理索引类型索引的使用场景案例演示&#xff1a;创建和使用索引 1.2 查询重写技术常见的查询重写方法 1.3 查询计划分析案例演示&#xff1a;使用EXPLAIN查看查询计划 二、D…

销售团队管理全面指南:从结构到流程

“除非卖出东西&#xff0c;否则就不能叫生意。” ——Thomas Watson的这段话表明&#xff0c;无论您经营哪个行业&#xff0c;销售都应该成为企业最重要的部分。您可能拥有出色的产品&#xff0c;但真正重要的是如何销售它。为此&#xff0c;您需要一支出色的销售团队&#xf…

书生大模型实战(从入门到进阶)L3-彩蛋岛-InternLM 1.8B 模型 Android 端侧部署实践

目录 1 环境准备 1.1 安装rust 1.2 安装Android Studio 1.3 设置环境变量 2 转换模型 2.1 安装mlc-llm 2.2 (可选)转换参数 2.3 (可选)生成配置 2.4 (可选)上传到huggingface 2.5 (可选) 测试转换的模型 3 打包运行 3.1 修改配置文件 3.2 运行打包命令 3.3 创建签…

gyp ERR node-gyp失败处理

当前版本: node v16.20.2 pnpm 8.14.3 npm 8.19.4 python失败 可以在微软的应用商店安装python node-gyp安装了和node一样的版本,然后失败 │ Building: C:\Program Files\nodejs\node.exe D:\data\work_code\data\xiangm\node_modules\.pnpm\node-gyp7.1.2\n… │ gyp inf…