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

栏目分类:帮助教程 发布时间:2025-11-27 阅读次数:44

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


harmonyos_logo


一、开始准备工作

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';


2. 定义状态变量用于显示语录

@State message: string = '点击获取打工人语录...';


3. 编写调用 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(); // 释放资源
  }
}


4. 在 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,并展示返回的幽默语录文本。


相关服务:

打工人语录

其他推荐OTHER API 更多>

开通会员专享福利
工单 客服