华为鸿蒙系统(HarmonyOS)调用天聚数行 API 教程

如何在在 HarmonyOS 应用中,通过 HTTP 请求调用 天聚数行API,并展示返回的语录内容。以下以调用"打工人语录"接口为例,可以参考使用。

一、开始准备工作

1. 注册账号并获取 API Key

首先,访问天聚数行官网注册账号并登录,返回接口市场搜索并申请「打工人语录」接口。 进入【控制台】 → 【数据管理】 → 获取你的 APIKEY(后续代码中需替换)。

2.创建 HarmonyOS 项目

使用 DevEco Studio 创建一个新的 Stage 模型 的 ArkTS 项目(推荐使用最新稳定版),确保项目支持网络请求权限。

3. 添加网络权限

在 module.json5 文件中添加网络权限:

复制代码
{
  "module": {
    // ...
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}
二、编写网络请求代码(ArkTS)
  1. 导入必要模块

在页面逻辑文件(如 MainPage.ets)顶部导入 @ohos.net.http:

复制代码
import http from '@ohos.net.http';
  1. 定义状态变量用于显示语录
复制代码
@State message: string = '点击获取打工人语录...';
  1. 编写调用 API 的函数
复制代码
private async fetchWorkQuote(): Promise<void> {
  const apiKey = '你的APIKEY'; // ←←← 替换为你自己的 API Key
  const url = `https://apis.tianapi.com/dgryl/index?key=${apiKey}`;

  let httpRequest = http.createHttp();
  try {
    const response = await httpRequest.request(url, {
      method: http.RequestMethod.GET,
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (response.responseCode === 200) {
      let result = JSON.parse(response.result as string);
      if (result.code === 200 && result.result?.content) {
        this.message = result.result.content;
      } else {
        this.message = '获取失败:' + (result.msg || '未知错误');
      }
    } else {
      this.message = `HTTP 错误:${response.responseCode}`;
    }
  } catch (error) {
    console.error('网络请求异常:', error);
    this.message = '网络请求失败,请检查网络或 API Key';
  } finally {
    httpRequest.destroy(); // 释放资源
  }
}
  1. 在 UI 中绑定按钮和文本
复制代码
Column() {
  Text(this.message)
    .fontSize(20)
    .textAlign(TextAlign.Center)
    .padding(20)
    .width('90%')

  Button('获取打工人语录')
    .onClick(() => {
      this.fetchWorkQuote();
    })
    .margin(20)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
三、完整示例代码(MainPage.ets)
复制代码
// MainPage.ets
import http from '@ohos.net.http';

@Entry
@Component
struct MainPage {
  @State message: string = '点击获取打工人语录...';

  private async fetchWorkQuote(): Promise<void> {
    const apiKey = '你的APIKEY'; // ←←← 务必替换!
    const url = `https://apis.tianapi.com/dgryl/index?key=${apiKey}`;

    let httpRequest = http.createHttp();
    try {
      const response = await httpRequest.request(url, {
        method: http.RequestMethod.GET,
        header: { 'Content-Type': 'application/json' }
      });

      if (response.responseCode === 200) {
        let result = JSON.parse(response.result as string);
        if (result.code === 200 && result.result?.content) {
          this.message = result.result.content;
        } else {
          this.message = 'API 返回错误:' + (result.msg || '无内容');
        }
      } else {
        this.message = `HTTP ${response.responseCode}`;
      }
    } catch (err) {
      console.error('请求失败:', err);
      this.message = '请求失败,请检查网络或 API Key';
    } finally {
      httpRequest.destroy();
    }
  }

  build() {
    Column() {
      Text(this.message)
        .fontSize(18)
        .textAlign(TextAlign.Center)
        .padding(20)
        .width('90%')
        .backgroundColor('#f0f0f0')
        .borderRadius(10)

      Button('获取打工人语录')
        .onClick(() => {
          this.fetchWorkQuote();
        })
        .width(200)
        .height(50)
        .margin(30)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
四、注意事项

API Key 安全:

不要将 APIKEY 硬编码在前端代码中(仅用于演示)

正式项目建议通过后端代理调用,避免密钥泄露

HTTPS 要求:

HarmonyOS 默认只允许 HTTPS 请求,天聚数行 API 支持 HTTPS,无需额外配置

调用频率限制:

普通会员每日限 100 次,注意不要超限(返回 code=150 表示配额不足)

错误处理:

建议根据返回的 code 字段做更细致的错误提示(参考文档中的错误码表)

五、建议和总结

可以将 API 调用封装为独立服务类,添加加载状态(Loading),实现支持自动刷新或定时轮询,并结合本地缓存避免重复请求。完成以上步骤后,你的 HarmonyOS 应用即可成功调用天聚数行「打工人语录」API,并展示返回的幽默语录文本。

相关推荐
Huang兄5 小时前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui
anyup1 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
Ranger09291 天前
鸿蒙开发新范式:Gpui
rust·harmonyos
Huang兄1 天前
鸿蒙-深色模式适配
harmonyos·arkts·arkui
BingoGo1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
SummerKaze3 天前
为鸿蒙开发者写一个 nvm:hmvm 的设计与实现
harmonyos
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端