HarmonyOS鸿蒙Next中基于Axios实现网络请求源码

HarmonyOS鸿蒙Next中基于Axios实现网络请求源码

介绍

本示例对Axios部分功能进行封装,通过axios.request()方法实现网络请求功能,用户可更改Config配置文件以访问不同地址。

基于 Axios 实现网络请求源码链接

效果预览

图片名称

实现思路

  1. package.json5文件中配置axios依赖。
  "dependencies": {
    "@ohos/axios": "^2.2.0"
  }
  1. 封装自定义工具类,封装请求方法。
  async request(url: string): Promise<Result> {
    let result: Result = {}
    let res: AxiosResponse = await axios.request({ url: url, method: 'get' })
    result.statue = res ? JSON.stringify(res.status) : '';
    result.data = res ? JSON.stringify(res.data) : '';
    result.statusText = res ? res.statusText : '';
    return result
  }
  1. 定义Config接口并实现。
  export const demoConfig1: DemoConfig = {
    baseUrl: getContext().resourceManager.getStringByNameSync('url_develop'), // 基础请求地址
    ......
  } 
  1. 调用工具类请求方法获取响应数据。
  this.startTime = new Date().getTime()
  this.axiosUtil.request(this.baseUrl)
    .then((res) => {
      this.status = res.statue
      this.message = res.data
      this.endTime = new Date().getTime()
      hilog.error(0x0000, 'testTag', '%{public}s', JSON.stringify(res));
    })
    .catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', 'err code == %{public}s msg == %{public}s', err.code,                   err.message);
    })

更多关于HarmonyOS鸿蒙Next中基于Axios实现网络请求源码的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS Next中实现网络请求可通过@ohos/net.http模块完成,无需依赖Axios。以下是核心代码示例:

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

let httpRequest = http.createHttp();
httpRequest.request(
  "https://api.example.com/data",
  {
    method: 'GET',
    header: { 'Content-Type': 'application/json' }
  },
  (err, data) => {
    if (!err) {
      console.log('Response:', data.result);
    } else {
      console.error('Error:', err);
    }
  }
);

关键点:

  1. 使用系统原生http模块
  2. 支持GET/POST等常用方法
  3. 回调方式处理响应
  4. 需在module.json5配置网络权限,

更多关于HarmonyOS鸿蒙Next中基于Axios实现网络请求源码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


这是一个很好的HarmonyOS Next中使用Axios进行网络请求的示例实现。我来分析下关键点:

  1. 依赖配置正确,使用@ohos/axios 2.2.0版本,这是官方维护的适配版本。

  2. 封装方式合理,通过request方法统一处理请求,返回Promise便于异步处理。建议可以:

  • 增加请求超时配置
  • 统一错误处理逻辑
  • 添加请求拦截器
  1. 配置管理做得不错,通过Config接口实现不同环境的URL配置,便于维护。

  2. 示例中包含了完整的请求生命周期处理:

  • 记录请求开始/结束时间
  • 处理响应数据
  • 错误日志记录
  1. 性能考虑:
  • 使用hilog记录日志而非console
  • 异步处理避免阻塞UI

这个实现可以作为HarmonyOS网络请求的基础模板,根据实际需求可以进一步扩展缓存、重试等机制。代码结构清晰,符合HarmonyOS开发规范。

回到顶部