华为鸿蒙系统(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,并展示返回的幽默语录文本。

相关推荐
TG:@yunlaoda360 云老大3 小时前
如何在华为云国际站代理商控制台进行基础状态核查的常见问题解答
数据库·华为云·php
BlackWolfSky3 小时前
鸿蒙加解密
华为·harmonyos
融云3 小时前
融云 4 款 SDK 首批通过 GIIC 鸿蒙生态评测
华为·harmonyos
讯方洋哥4 小时前
HarmonyOS应用开发—页面路由
华为·harmonyos
鸿蒙开发工程师—阿辉4 小时前
HarmonyOS 5 高效使用命令:HDC 基本使用
华为·harmonyos
程序员在囧途4 小时前
Sora2 25 秒视频 API 国内直连!10 积分/次,稳定秒退任务,支持 avatar & Remix(附 PHP 接入教程)
后端·开源·php
峰顶听歌的鲸鱼4 小时前
15.docker:网络
运维·网络·docker·容器·云计算·php·学习方法
catchadmin4 小时前
使用 PHP 和 WebSocket 构建实时聊天应用 完整指南
开发语言·websocket·php
梧桐ty4 小时前
鸿蒙 + Flutter:构建万物互联时代的跨平台应用新范式
flutter·华为·harmonyos