HarmonyOS NEXT - 三方库axios的使用和封装

news2024/9/21 4:31:55

demo 地址: https://github.com/iotjin/JhHarmonyDemo
代码不定时更新,请前往github查看最新代码

在demo中这些组件和工具类都通过module实现了,具体可以参考HarmonyOS NEXT - 通过 module 模块化引用公共组件和utils

HarmonyOS NEXT - 三方库axios的使用和封装

  • 一些ohpm 命令
  • 安装axios
  • 直接使用
  • 封装后使用
  • 封装代码
  • Request.ets
  • HttpUtils.ets
  • APIs.ets

参考:
鸿蒙HarmonyOS开发:如何使用第三方库,加速应用开发
掌握鸿蒙网络请求:Axios网络请求库快速入门

一些ohpm 命令

ohpm 官方文档

ohpm ls // 列出已安装的三方库
ohpm install @ohos/axios // 安装三方库
ohpm -v // 查询 ohpm cli 安装版本
ohpm update @ohos/axios
ohpm uninstall @ohos/axios

axios 鸿蒙库地址

安装axios

方式1:

ohpm install @ohos/axios

OpenHarmony ohpm 环境配置等更多内容,请参考如何安装 OpenHarmony ohpm 包

方式2:

直接在顶层的oh-package.json5中的dependencies 设置三方包依赖
“dependencies”: { “@ohos/axios”: “^2.2.2” },

{
  "modelVersion": "5.0.0",
  "description": "Please describe the basic information.",
  "dependencies": {
    "@ohos/axios": "^2.2.2"
  },
  "devDependencies": {
    "@ohos/hypium": "1.0.18",
    "@ohos/hamock": "1.0.0"
  },
  "dynamicDependencies": {}
}

点击 Sync Now同步一下

在这里插入图片描述
然后在当前目录的 oh_modules 目录下就可以看到了

在这里插入图片描述

直接使用

要请求网络数据,首先需要申请权限,需要在module.json5文件中设置网络访问权限

    "requestPermissions": [
      {"name": "ohos.permission.INTERNET"}
    ]

调用 axios

import axios, { AxiosError, AxiosResponse } from '@ohos/axios';
import { APIs } from './APIs';

get

    const url = APIs.apiPrefix + APIs.getPage;
    const params: object = Object({ 'page': 0, 'limit': 10 })
    axios.get(url, { params: params }).then((res: AxiosResponse) => {
      console.log("get - 返回数据:" + JSON.stringify(res.data));
      console.log(res.data['msg']);
      this.text = JSON.stringify(res.data);
    }).catch((err: AxiosError) => {
      console.log("result:" + err.message);
    });

post

    const url = APIs.apiPrefix + APIs.getSimpleDictList;
    const params: object = Object({ 'page': 0, 'limit': 10 })
    axios.post(url, params).then((res: AxiosResponse) => {
      console.log("post - 返回数据:" + JSON.stringify(res.data));
      console.log(res.data['msg']);
      this.text = JSON.stringify(res.data);
    }).catch((err: AxiosError) => {
      console.log("result:" + err.message);
    });

结果:

在这里插入图片描述

在这里插入图片描述

封装后使用

封装了2层,第一次是基础封装Request,第二次又添加了loading和返回错误弹框提示HttpUtils,这样在项目中以后只使用第二次封装的代码,如果后期需要调整会方便一点

Request

import { Request } from 'JhCommon';
import { AxiosError, AxiosResponse } from '@ohos/axios';

   const url = APIs.getPage;
   const params: object = Object({ 'page': 0, 'limit': 10 })
   Request({ url: url, method: 'get', params: params }).then((res: AxiosResponse) => {
     // res 返回的 {code,suc,msg,data}
     console.log("封装 - get - 返回数据:" + JSON.stringify(res['data']));
     console.log("msg:" + res['msg']);
   }).catch((err: AxiosError) => {
     console.log("err:" + err.message);
   });

HttpUtils

import { APIs, ErrorType, HttpUtils, ResType } from 'JhCommon';

    HttpUtils.get(url, params).then((res: ResType) => {
      console.log("二次封装 - get - 返回数据:" + JSON.stringify(res));
      console.log("二次封装 - get - 返回数据:" + JSON.stringify(res.data));
      console.log('code:', res.code)
      console.log('msg:', res.msg)
      this.text1 = JSON.stringify(res.data);
    }).catch((err: ErrorType) => {
      console.log("err:" + err.msg);
    });

    const url = APIs.apiPrefix + APIs.getSimpleDictList;
    const params: object = Object({ 'page': 0, 'limit': 10 })

    HttpUtils.post(url, params).then((res: ResType) => {
      console.log("二次封装 - post - 返回数据:" + JSON.stringify(res));
      console.log("二次封装 - post - 返回数据:" + JSON.stringify(res.data));
      console.log('code:', res.code)
      console.log('msg:', res.msg)
      this.text2 = JSON.stringify(res.data);
    }).catch((err: ErrorType) => {
      console.log("err:" + err.msg);
    });

封装代码

  • 网络请求用到的loading和本地存储:

loading组件的实现看这里 HarmonyOS NEXT - Toast和Loading使用
数据持久化看这里 HarmonyOS NEXT - 数据持久化存储(key,value进行AES加密处理)

Request.ets

///  HttpUtils.ets
///
///  Created by iotjin on 2024/08/09. 
///  description: 网络请求工具类(axios二次封装)

import { AxiosError, AxiosResponse } from '@ohos/axios';
import { JhProgressHUD } from '../components/JhProgressHUD';
import Request from './Request';

// 日志开关
const isOpenLog = true

export enum Method {
  get = 'get',
  post = 'post',
  put = 'put',
  patch = 'patch',
  delete = 'delete',
  head = 'head',
}

export interface ResType {
  code: number
  msg: string
  suc: boolean
  data: ESObject
  total: number
}

export interface ErrorType {
  code: number
  msg: string
}

export class HttpUtils {
  public static get(
    url: string,
    params?: Record<string, ESObject>,
    loadingText: string = "加载中..."
  ) {
    return HttpUtils.request(Method.get, url, params, loadingText)
  }

  public static post(
    url: string,
    params?: Record<string, ESObject>,
    loadingText: string = "加载中..."
  ) {
    return HttpUtils.request(Method.post, url, params, loadingText)
  }


  public static request(
    method: Method,
    url: string,
    params?: Record<string, ESObject>,
    loadingText: string = "加载中..."
  ): Promise<ResType> {
    return new Promise<ResType>((resolve, reject) => {

      // 参数处理(如果需要加密等统一参数)
      if (isOpenLog) {
        console.log('---------- HttpUtils URL ----------')
        console.log(url)
        console.log('---------- HttpUtils params ----------')
        console.log(JSON.stringify(params))
      }

      let queryParameters: ESObject = null
      let data: ESObject = null
      if (method == Method.get) {
        queryParameters = params
      }
      if (method == Method.post) {
        data = params
      }

      if (loadingText != null && loadingText.length > 0) {
        JhProgressHUD.showLoadingText(loadingText)
      }

      Request({
        url: url,
        method: method,
        params: queryParameters,
        data: data,
      }).then((res: AxiosResponse) => {
        if (isOpenLog) {
          console.log('---------- HttpUtils response ----------')
          console.log(JSON.stringify(res))
        }
        if (loadingText != null && loadingText.length > 0) {
          JhProgressHUD.hide()
        }

        const code: number = res['code']
        const msg: string = res['msg']
        if (code === 200) {
          let result: ResType = {
            code: code,
            msg: msg,
            suc: res['suc'],
            data: res['data'],
            total: res['total'],
          }
          resolve(result)
        } else {
          JhProgressHUD.showText(msg || '系统错误')
          reject({ code: code, msg: msg })
        }
      }).catch((err: AxiosError) => {
        console.log("HttpUtils err:" + err.message)
        if (loadingText != null && loadingText.length > 0) {
          JhProgressHUD.hide()
        }
        JhProgressHUD.showText(err.message || '系统错误')
        reject({ code: err.code, msg: err.message })
      })
    })
  }
}

HttpUtils.ets

///  HttpUtils.ets
///
///  Created by iotjin on 2024/08/09. 
///  description: 网络请求工具类(axios二次封装)

import { AxiosError, AxiosResponse } from '@ohos/axios';
import { JhProgressHUD } from '../components/JhProgressHUD';
import Request from './Request';

// 日志开关
const isOpenLog = true

export enum Method {
  get = 'get',
  post = 'post',
  put = 'put',
  patch = 'patch',
  delete = 'delete',
  head = 'head',
}

export interface ResType {
  code: number
  msg: string
  suc: boolean
  data: ESObject
  total: number
}

export interface ErrorType {
  code: number
  msg: string
}

export class HttpUtils {
  public static get(
    url: string,
    params?: Record<string, ESObject>,
    loadingText: string = "加载中..."
  ) {
    return HttpUtils.request(Method.get, url, params, loadingText)
  }

  public static post(
    url: string,
    params?: Record<string, ESObject>,
    loadingText: string = "加载中..."
  ) {
    return HttpUtils.request(Method.post, url, params, loadingText)
  }


  public static request(
    method: Method,
    url: string,
    params?: Record<string, ESObject>,
    loadingText: string = "加载中..."
  ): Promise<ResType> {
    return new Promise<ResType>((resolve, reject) => {

      // 参数处理(如果需要加密等统一参数)
      if (isOpenLog) {
        console.log('---------- HttpUtils URL ----------')
        console.log(url)
        console.log('---------- HttpUtils params ----------')
        console.log(JSON.stringify(params))
      }

      let queryParameters: ESObject = null
      let data: ESObject = null
      if (method == Method.get) {
        queryParameters = params
      }
      if (method == Method.post) {
        data = params
      }

      if (loadingText != null && loadingText.length > 0) {
        JhProgressHUD.showLoadingText(loadingText)
      }

      Request({
        url: url,
        method: method,
        params: queryParameters,
        data: data,
      }).then((res: AxiosResponse) => {
        if (isOpenLog) {
          console.log('---------- HttpUtils response ----------')
          console.log(JSON.stringify(res))
        }
        if (loadingText != null && loadingText.length > 0) {
          JhProgressHUD.hide()
        }

        const code: number = res['code']
        const msg: string = res['msg']
        if (code === 200) {
          let result: ResType = {
            code: code,
            msg: msg,
            suc: res['suc'],
            data: res['data'],
            total: res['total'],
          }
          resolve(result)
        } else {
          JhProgressHUD.showText(msg || '系统错误')
          reject({ code: code, msg: msg })
        }
      }).catch((err: AxiosError) => {
        console.log("HttpUtils err:" + err.message)
        if (loadingText != null && loadingText.length > 0) {
          JhProgressHUD.hide()
        }
        JhProgressHUD.showText(err.message || '系统错误')
        reject({ code: err.code, msg: err.message })
      })
    })
  }
}

APIs.ets

///  APIs.ets
///
///  Created by iotjin on 2024/08/08.
///  description: api管理

export class APIs {
  /// url 前缀
  static readonly apiPrefix: string = 'https://console-mock.apipost.cn/mock/e7a66e3e-1b07-4902-9beb-366dd35ae67d/v1/api'
  /// 登录接口
  static readonly login: string = '/mock/login'
  /// 刷新token
  static readonly refreshToken: string = '/mock/refreshToken'
  /// 获取分页数据
  static readonly getPage: string = '/mock/pages'
  /// 获取分页分组数据
  static readonly getGroupPage: string = '/mock/groupPages'
  /// 获取固定数据
  static readonly getSimpleDictList: string = '/mock/simpleDictList'
  /// 获取固定数据
  static readonly getSimpleDict: string = '/mock/dict'
  /// 微信朋友圈
  static readonly getFriendsCircleList: string = '/mock/wx/moments'
}

在demo中这些组件和工具类都通过module实现了,具体可以参考HarmonyOS NEXT - 通过 module 模块化引用公共组件和utils

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2044389.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Matplotlib入门与进阶:数据可视化的强大工具

Matplotlib入门与进阶&#xff1a;数据可视化的强大工具 在当今数据驱动的世界中&#xff0c;数据可视化成为了数据分析的重要一环。数据可视化不仅能够帮助开发者理解和分析数据&#xff0c;还能使数据展示更具说服力。本文将详细介绍Python中的2D绘图库——Matplotlib。通过…

通过共享目录上传后门

本文来自无问社区&#xff0c;更多实战内容可前往查看http://www.wwlib.cn/index.php/artread/artid/13337.html 操作步骤 枚举目标主机开启的共享服务信息&#xff1a;10.0.0.6 smbclient -L //10.0.0.6 -U spotWARNING: The "syslog" option is deprecated Ente…

flink车联网项目前篇:数据开发(第66天)

系列文章目录 03_数据仓库开发 开发规范 1.1 数据库划分规范 1.2 表命名规范 1.3 表字段类型规范开发前准备 3.1 业务系统表 3.2 数据导入 04_维度主题相关表结构 1.1 dim_area - 城市字典表 1.2 dim_car_info - 车辆信息表 1.3 dim_car_vendor - 车队信息表 1.4 dim_date_wo…

虹科技术|优化始于数据:Baby-LIN设备如何高效存储总线数据?

记录汽车总线数据对于监控汽车电子控制单元&#xff08;ECU&#xff09;间的通信和诊断网络故障具有重要意义。通过记录测试时的总线数据&#xff0c;不仅可以监控产品是否按照预期运行&#xff0c;还能追踪特定错误或故障背后的原因&#xff0c;这对确保汽车产品质量和性能至关…

MySQL查询居然不区分大小写

MySQL查询居然不区分大小写 事故现场真实原因BINARY 关键字总结MySQL 为什么要这样设计呢&#xff1f;解决方案修改排序规则binary &#xff01;&#xff01;&#xff01;&#xff01;&#xff01;懵逼了&#xff0c; MySQL 查询居然不区分大小写&#xff0c;第一次听到这么陌…

实验9 根据材料编程《汇编语言》- 王爽

1. 需求 编程&#xff1a;在屏幕中间分别显示绿色、绿底红色、白底蓝色的字符串 welcome to masm! 2. 分析 &#xff08;1&#xff09;材料中提到&#xff0c;一个在屏幕上显示的字符&#xff0c;具有前景&#xff08;字符色&#xff09;和背景&#xff08;底色&#xff09;…

[000-01-030].第7节:Zookeeper工作原理

1.Zookeeper工作原理&#xff1a; 1.1.Zookeeper的工作机制 1.Zookeeper从设计模式角度来理解&#xff1a;是一个基于观察者模式设计的分布式服务管理框架&#xff1b;2.Zookeeper负责存储和管理大家都关心的数据&#xff0c;然后接受观察者的注册&#xff0c;一旦这些数据的…

来了,秋天的第一个POC

立秋就这么水灵灵地过了 又到了“秋天的第一杯奶茶”刷屏的时刻 而我们要追求的是“秋天的第一个POC” 做好变强的准备了吗 Yak POC编写&#xff0c;这一篇就够了 文章中指代的POC仅指使用 Yaklang 编程语言编写的POC 在此篇文章中就详细描述 Yaklang 语法的学习了&#x…

【昱合昇天窗】消防排烟天窗设计使用需注意问题

消防排烟天窗在设计和使用过程中&#xff0c;需要避免出现以下三个问题&#xff0c;以免影响其排烟效果和安全性。1、只关注价格 很多人在选择消防排烟天窗时&#xff0c;只关心天窗的价格&#xff0c;不重视天窗型号、配置选择是否满足厂房需求。这样做的坏处在于安装的天窗可…

还在画恐怖片?局部重绘,艺术再创造 —— Stable diffusion inPainting功能详解与实战指南

前言 在AI绘画的世界里&#xff0c;我们常常面临这样的困境&#xff1a;一幅作品&#xff0c;除了手部姿势、面部表情其他都很完美&#xff1b;这时候&#xff0c;如果要重新生成整幅画&#xff0c;不仅效率低下&#xff0c;而且可能会破坏原本满意的部分。幸好&#xff0c;St…

JAVA毕业设计|(免费)ssm视康眼镜网店销售系统的包含文档代码讲解

收藏点赞不迷路 关注作者有好处 编号&#xff1a;ssm538 ssm视康眼镜网店销售系统的 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SpringSpringMVCMyBatisVue 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 文末获取源码 1.系统展示 2.万字文档展示 …

为什么MySql使用B+树

mysql索引为什么选择B树&#xff1f; 在回答这个问题之前&#xff0c;得先了解一个概念&#xff0c;页的概念。页是InnoDB中数据管理的最小单位。当我们查询数据时&#xff0c;其是以页为单位&#xff0c;将磁盘中的数据加载到缓冲池中的。同理&#xff0c;更新数据也是以页为…

数据库实验一 创建数据库

一&#xff0e;实验目的 1.学会数据表的创建&#xff1b; 2.加深对表间关系的理解&#xff1b; 3.理解数据库中数据的简单查询方法和应用。 二. 实验内容 1.题目要求 给定一个实际问题&#xff0c;实际应用问题的模式设计中至少要包括3个基本表。应用问题是供应商给工程供…

被嫌弃的35岁程序员,竟找到了职业的新出路:PMP项目管理

35岁&#xff0c;本应是事业发展的高峰期。更多听到的却是35岁职场天花板&#xff0c;特别是IT从业者&#xff0c;35岁就好像是一道迈不过的坎&#xff1a;多年的工作经验&#xff0c;在35岁的生理年龄面前&#xff0c;一文不值。 IT从业者若想安然度过“35岁危机”&#xff0…

【RISC-V设计-14】- RISC-V处理器设计K0A之打印输出

【RISC-V设计-14】- RISC-V处理器设计K0A之打印输出 文章目录 【RISC-V设计-14】- RISC-V处理器设计K0A之打印输出1.简介2.验证用例3.软件代码4.链接脚本5.编译脚本6.仿真结果6.1 复位结束6.2 运行成功6.3 终端打印 7.总结 1.简介 本文将详细阐述如何利用 printf 来打印字符串…

做自媒体博主如何使用外网视频素材!

想成为视频博主却不知道外网视频怎么下载&#xff1f;看这里&#xff01; 在这个信息爆炸的时代&#xff0c;做一名视频博主无疑是展现自我、分享创意的绝佳方式。但当我们想要获取更多灵感&#xff0c;从外网的精彩视频中学习时&#xff0c;却常常被下载的问题难住。 其实&…

【启明智显技术分享】工业级HMI芯片Model3A开发过程中问题记录笔记

一、Model3A芯片介绍 Model3A是启明智显针对工业、行业以及车载产品市场推出的一款高性能、低成本的工业级HMI&#xff08;Human-Machine Interface&#xff0c;人机界面&#xff09;芯片。该芯片主要应用于工业自动化、智能终端HMI、车载仪表盘、两轮车彩屏仪表、串口屏、智能…

无人机航拍与ArcGIS融合实战:从地表观测到空间数据可视化的全方位指南!无人机图像拼接数据处理与分析、可视化与制图

目录 第一章 无人机航拍基本流程、航线规划与飞行实践 第二章 无人机图像拼接软件的学习与操作实践 第三章 无人机图像拼接典型案例详解 第四章 无人机图像拼接数据在GIS中的处理与分析 第五章 无人机图像拼接数据在GIS中的可视化与制图 第六章 综合案例:无人机航拍植被动…

Docker 部署 XXL-JOB

Docker 部署 XXL-JOB 目录 引言环境准备创建 MySQL 用户并授予权限使用 Docker 部署 XXL-JOB配置 XXL-JOB验证部署总结 1. 引言 XXL-JOB 是一个开源的分布式任务调度平台&#xff0c;旨在简化定时任务的管理和调度操作。其强大的功能和灵活性&#xff0c;使其在互联网公司和…

SSH 隧道方式连接 MySQL 服务器

SSH 隧道方式连接 MySQL 服务器 1 安装 MySQL 客户端工具1.1 Navicat1.2 MySQL Workbench1.2.1 查看本机系统类型1.2.2 安装 Visual C 20191.2.3 安装 MySQL Workbench 2 SSH 隧道方式连接数据库2.1 Navicat2.1.1 SSH 连服务器2.1.2 本地连数据库 2.2 MySQL Workbench 本文介绍…