文档开发者中心
我的

HarmonyOS 天气预报对接完整技术实战

浏览83发布于2026-07-16 04:17河南

一、前言

在鸿蒙生态开发中,天气功能是生活类、出行类、工具类 App 高频刚需能力。当前鸿蒙提供两套天气预报对接方案:

  1. 官方 Weather Service Kit(系统应用专用):华为原生气象数据,精度高、支持分钟级降水、气象预警、潮汐、生活指数,但仅系统应用可开通,普通第三方商用 App 无法使用Huawei Dev...;
  2. 第三方气象 API 通用方案(第三方 App 首选):和风天气、心知天气、阿里云气象等,普通开发者可直接申请 Key,适配所有 HarmonyOS NEXT/5/6 设备,无应用类型限制。

本文两套方案完整覆盖,包含开发环境、权限配置、ArkTS 代码封装、页面渲染、异常处理、常见踩坑排查,适配 HarmonyOS NEXT(API 12+)。

二、两套方案选型对比

表格

方案 适用应用 优势 限制
Weather Service Kit 系统内置应用、厂商定制应用 毫秒级格点气象、分钟降水、官方鉴权、无第三方网络依赖 第三方普通 App 无法开通,AGC 后台无服务开关Harmo...
第三方气象 API(和风) 所有第三方 App、元服务、卡片 免费个人额度、文档完善、支持经纬度 / 城市查询 需要网络请求、自行处理缓存、超时、限流

下文优先讲解第三方通用方案(90% 开发者使用),文末补充官方 Weather Service Kit 集成代码。

三、通用前置开发环境准备

3.1 软硬件环境

  • DevEco Studio NEXT Beta / 5.0.5+
  • HarmonyOS SDK API 12 及以上(NEXT)
  • 真机调试(模拟器定位、网络权限存在兼容问题)
  • AppGallery Connect 项目(仅官方 Kit 需要,第三方 API 无需)

3.2 基础权限配置(module.json5)

无论哪种方案,必须声明网络权限;如需自动定位获取本地天气,追加位置权限。

json

收起
自动换行
深色代码主题
复制
{
  "module": {
    "name": "entry",
    "type": "app",
    "requestPermissions": [
      // 网络请求必备,第三方API/官方Kit均需要
      {
        "name": "ohos.permission.INTERNET",
        "reason": "$string:internet_permission_reason"
      },
      // 可选:自动获取当前定位经纬度
      {
        "name": "ohos.permission.LOCATION",
        "reason": "$string:location_permission_reason"
      }
    ]
  }
}

四、方案一:第三方气象 API 对接(和风天气,通用第三方)

4.1 前期准备

  1. 前往和风开发者平台注册,创建应用,获取KEY;
  2. 核心接口:
    • 实时天气:/v7/now
    • 7 天逐日预报:/v7/weather/7d
    • 24 小时逐小时预报:/v7/weather/24h
  3. 接口入参:location支持城市 ID、经纬度;key为必填鉴权参数。

4.2 项目分层结构

plaintext

收起
自动换行
深色代码主题
复制
entry/src/main/ets
├── model
│   └── WeatherModel.ets      // 天气数据实体模型
├── utils
│   └── HttpUtil.ets          // 统一网络请求封装
├── service
│   └── WeatherApi.ets        // 气象API业务封装
└── pages
    └── Index.ets             // 天气展示页面

4.3 步骤 1:封装通用网络请求工具 HttpUtil.ets

基于鸿蒙原生@ohos.net.http封装统一 GET/POST,统一异常捕获、状态码判断。

typescript

运行

收起
自动换行
深色代码主题
复制
import http from '@ohos.net.http';

export class HttpUtil {
  static async get<T>(url: string): Promise<T> {
    const httpReq = http.createHttp();
    try {
      const res = await httpReq.request(url, {
        method: http.RequestMethod.GET,
        connectTimeout: 10000,
        readTimeout: 10000
      });
      if (res.responseCode !== 200) {
        throw new Error(`请求失败,状态码:${res.responseCode}`);
      }
      const data = JSON.parse(res.result as string) as T;
      return data;
    } catch (err) {
      console.error("网络请求异常:", JSON.stringify(err));
      throw err;
    } finally {
      httpReq.destroy();
    }
  }
}

4.4 步骤 2:定义天气数据模型 WeatherModel.ets

typescript

运行

收起
自动换行
深色代码主题
复制
// 实时天气实体
export interface RealTimeWeather {
  temp: string;        // 实时温度
  feelsLike: string;   // 体感温度
  text: string;        // 天气状况文字(晴/雨)
  icon: string;        // 天气图标编码
  windDir: string;     // 风向
  humidity: string;    // 湿度
  obsTime: string;     // 更新时间
}

// 单日预报
export interface DailyWeather {
  fxDate: string;
  tempMax: string;
  tempMin: string;
  textDay: string;
  textNight: string;
}

// 接口返回顶层结构
export interface WeatherResp {
  code: string;
  now: RealTimeWeather;
  daily: DailyWeather[];
}

4.5 步骤 3:封装气象 API 服务 WeatherApi.ets

统一管理域名、密钥、请求逻辑,解耦页面业务。

typescript

运行

收起
自动换行
深色代码主题
复制
import { HttpUtil } from '../utils/HttpUtil';
import { WeatherResp } from '../model/WeatherModel';

// 替换为你自己的和风KEY
const API_KEY = "你的和风天气KEY";
const BASE_URL = "https://devapi.qweather.com/v7";

export class WeatherApiService {
  /**
   * 根据经纬度查询天气
   * @param lon 经度
   * @param lat 纬度
   */
  static async getWeatherByLonLat(lon: number, lat: number): Promise<WeatherResp> {
    // 拼接实时天气+7天预报双接口,也可分开请求
    const nowUrl = `${BASE_URL}/now?key=${API_KEY}&location=${lon},${lat}`;
    const dailyUrl = `${BASE_URL}/weather/7d?key=${API_KEY}&location=${lon},${lat}`;

    const nowData = await HttpUtil.get<{ code: string; now: RealTimeWeather }>(nowUrl);
    const dailyData = await HttpUtil.get<{ code: string; daily: DailyWeather[] }>(dailyUrl);

    if (nowData.code !== "200" || dailyData.code !== "200") {
      throw new Error("气象接口返回数据异常");
    }

    return {
      code: "200",
      now: nowData.now,
      daily: dailyData.daily
    };
  }

  /**
   * 根据城市名称查询天气
   */
  static async getWeatherByCity(cityName: string): Promise<WeatherResp> {
    // 先根据城市名获取locationID,再查询天气
    const cityUrl = `https://geoapi.qweather.com/v2/city/lookup?key=${API_KEY}&location=${cityName}`;
    const cityRes = await HttpUtil.get<{ code: string; location: Array<{ id: string }> }>(cityUrl);
    if (cityRes.code !== "200" || cityRes.location.length === 0) {
      throw new Error("未查询到该城市");
    }
    const locId = cityRes.location[0].id;
    return this.getWeatherByLonLat(Number(locId), 0);
  }
}

4.6 步骤 4:ArkTS 页面渲染 Index.ets

完成按钮触发查询、状态加载、天气数据展示、异常提示。

typescript

运行

收起
自动换行
深色代码主题
复制
import { WeatherApiService } from '../service/WeatherApi';
import { RealTimeWeather, DailyWeather } from '../model/WeatherModel';

@Entry
@Component
struct WeatherPage {
  @State isLoading: boolean = false;
  @State realWeather: RealTimeWeather | null = null;
  @State dailyList: DailyWeather[] = [];
  @State errorMsg: string = "";

  // 查询指定经纬度天气(示例:北京)
  async queryWeather() {
    this.isLoading = true;
    this.errorMsg = "";
    try {
      const res = await WeatherApiService.getWeatherByLonLat(116.40, 39.90);
      this.realWeather = res.now;
      this.dailyList = res.daily;
    } catch (err: Error) {
      this.errorMsg = err.message;
    } finally {
      this.isLoading = false;
    }
  }

  @Builder CurrentWeatherCard() {
    if (!this.realWeather) return;
    Column() {
      Text(`${this.realWeather.temp}℃`)
        .fontSize(60)
        .fontWeight(FontWeight.Light)
      Text(this.realWeather.text)
        .fontSize(24)
        .margin({ bottom: 10 })
      Row() {
        Text(`体感${this.realWeather.feelsLike}℃ 湿度${this.realWeather.humidity}%`)
        Text(`风向${this.realWeather.windDir}`).margin({ left: 10 })
      }
    }
    .width("100%")
    .padding(20)
    .background("#409EFF")
    .borderRadius(16)
  }

  build() {
    Column() {
      Button("查询北京天气", { stateEffect: true })
        .margin({ bottom: 20 })
        .onClick(() => this.queryWeather())
        .enabled(!this.isLoading)

      if (this.isLoading) {
        LoadingProgress().width(50).height(50)
      } else if (this.errorMsg) {
        Text(this.errorMsg).fontColor(Color.Red)
      } else {
        this.CurrentWeatherCard()
        List({ space: 10 }) {
          ForEach(this.dailyList, (item: DailyWeather) => {
            ListItem() {
              Row() {
                Text(item.fxDate).width(100)
                Text(`${item.textDay}/${item.textNight}`).layoutWeight(1)
                Text(`${item.tempMin}~${item.tempMax}℃`)
              }
              .width("100%")
              .padding(10)
              .background("#f5f5f5")
              .borderRadius(8)
            }
          })
        }
        .margin({ top: 15 })
        .layoutWeight(1)
      }
    }
    .width("100%")
    .height("100%")
    .padding(15)
  }
}

4.7 优化方案(生产环境必备)

  1. 本地缓存:使用@ohos.data.preferences缓存天气数据,30 分钟内复用缓存,减少网络请求;
  2. 定位集成:接入 Location Kit 获取用户当前经纬度,自动查询本地天气;
  3. 限流处理:第三方 API 存在免费额度限制,增加请求间隔、失败重试机制;
  4. 离线降级:无网络时展示缓存历史天气,给出友好提示;
  5. 卡片联动:服务卡片定时调用天气接口,动态更新桌面小组件。

五、方案二:官方 Weather Service Kit(系统应用专用)

5.1 开发前置约束

  1. 仅系统应用、厂商预装 App 可开通,第三方商用 App 无法使用;
  2. 必须在 AppGallery Connect 后台开通「天气服务」,配置应用签名指纹鉴权;
  3. SDK 最低版本:HarmonyOS 5.0.5+ / NEXT API 12+;
  4. 无需第三方网络密钥,鸿蒙底层统一鉴权气象数据源。

5.2 AGC 后台开通步骤

  1. 登录 AppGallery Connect → 项目 → 对应鸿蒙应用;
  2. 开放能力管理 → 搜索 Weather Service Kit,开启开关保存;
  3. 配置调试 / 发布签名证书指纹,否则接口返回 1011900001 鉴权错误Huawei Dev...。

5.3 核心 ArkTS 调用代码

typescript

运行

收起
自动换行
深色代码主题
复制
import { weatherService } from '@kit.WeatherServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const DOMAIN = 0x0001;
const TAG = "WeatherKitDemo";

@Entry
@Component
struct WeatherKitPage {
  lat: number = 39.90;
  lon: number = 116.40;

  async queryOfficialWeather() {
    // 构造请求对象,limitedDatasets按需裁剪数据,降低时延
    const req: weatherService.WeatherRequest = {
      location: {
        latitude: this.lat,
        longitude: this.lon
      },
      // 仅请求实时天气+7天预报+气象预警
      limitedDatasets: [
        weatherService.Dataset.CURRENT,
        weatherService.Dataset.DAILY,
        weatherService.Dataset.ALERTS
      ]
    };
    try {
      const weatherRes = await weatherService.getWeather(req);
      // 实时天气
      if (weatherRes.current) {
        hilog.info(DOMAIN, TAG, `实时温度:${weatherRes.current.temperature}`);
      }
      // 逐日预报
      if (weatherRes.daily?.length) {
        hilog.info(DOMAIN, TAG, `明日最低温:${weatherRes.daily[1].tempMin}`);
      }
      // 气象预警
      if (weatherRes.alerts?.length) {
        hilog.info(DOMAIN, TAG, `预警:${weatherRes.alerts[0].title}`);
      }
    } catch (err) {
      const bizErr = err as BusinessError;
      hilog.error(DOMAIN, TAG, `查询失败 code:${bizErr.code}, msg:${bizErr.message}`);
    }
  }

  build() {
    Column() {
      Button("调用官方天气服务").onClick(() => this.queryOfficialWeather())
    }
    .width("100%")
    .height("100%")
  }
}

5.4 支持的完整气象数据集

通过limitedDatasets按需选择,减少传输体积:

  1. CURRENT:实时实况温度、湿度、风力;
  2. DAILY:10 日逐日预报;
  3. HOURLY:48 小时逐小时预报;
  4. MINUTE:未来 2 小时分钟级降水;
  5. ALERTS:气象局气象预警;
  6. INDICES:穿衣、紫外线、晾晒生活指数;
  7. TIDES:沿海城市潮汐数据。

六、常见报错与问题排查

6.1 第三方 API 方案问题

  1. 网络请求超时
    • 原因:未添加ohos.permission.INTERNET;模拟器网络异常;接口域名未放行;
    • 解决:补全权限,使用真机调试,延长超时时间。
  2. code=401/403
    • 密钥错误、额度耗尽、应用未审核;更换 KEY 或升级付费套餐。
  3. 城市查询无数据
    • 城市名称拼写错误,改用经纬度查询更稳定。

6.2 Weather Service Kit 官方方案报错

  1. 错误码 1011900001
    • 未开通天气服务 / 签名指纹配置错误;重新在 AGC 开启能力并配置证书Huawei Dev...。
  2. 无任何天气数据返回
    • 目标区域无预警、无潮汐、无分钟降水属于正常现象;检查limitedDatasets是否包含 CURRENT/DAILY。
  3. 调用无响应
    • 应用为第三方普通 App,官方 Kit 不开放,改用第三方气象 API。

七、生产环境最佳实践

  1. 数据按需拉取:官方 Kit 使用limitedDatasets;第三方 API 只请求业务需要的接口,减少带宽与耗时;
  2. 缓存策略:实时天气缓存 30 分钟,逐日预报缓存 2 小时,避免高频重复请求;
  3. 权限动态申请:定位权限采用动态弹窗申请,而非静态直接声明;
  4. 多端自适应:手机 / 平板 / 穿戴设备区分 UI 布局,穿戴端仅展示核心温湿度;
  5. 降级兜底:网络异常、接口限流时展示本地缓存历史天气,不空白页面;
  6. 卡片定时更新:桌面天气小组件设置 30 分钟自动刷新,避免频繁后台请求。

八、总结

  1. 第三方普通 App、元服务:优先选择和风 / 心知天气等第三方 API,无应用类型限制、接入门槛低,本文方案一可直接落地;
  2. 系统预装、厂商定制应用:使用官方 Weather Service Kit,数据精度更高、支持分钟降水、气象预警等专业气象能力;
  3. 开发核心流程统一:权限声明 → 网络 / 定位封装 → 数据模型定义 → 业务服务层解耦 → ArkTS 页面渲染 → 异常缓存兜底;
  4. 开发避坑重点:真机调试、权限完整配置、鉴权密钥 / 签名正确、按需裁剪气象数据减少请求耗时。
收藏
0
回复
0
分享
全部评论
暂无评论
暂无评论
写评论
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。
发表
我要写文章
目录 收起
一、前言
二、两套方案选型对比
三、通用前置开发环境准备
3.1 软硬件环境
3.2 基础权限配置(module.json5)
四、方案一:第三方气象 API 对接(和风天气,通用第三方)
4.1 前期准备
4.2 项目分层结构
4.3 步骤 1:封装通用网络请求工具 HttpUtil.ets
4.4 步骤 2:定义天气数据模型 WeatherModel.ets
4.5 步骤 3:封装气象 API 服务 WeatherApi.ets
4.6 步骤 4:ArkTS 页面渲染 Index.ets
4.7 优化方案(生产环境必备)
五、方案二:官方 Weather Service Kit(系统应用专用)
5.1 开发前置约束
5.2 AGC 后台开通步骤
5.3 核心 ArkTS 调用代码
5.4 支持的完整气象数据集
六、常见报错与问题排查
6.1 第三方 API 方案问题
6.2 Weather Service Kit 官方方案报错
七、生产环境最佳实践
八、总结
了解社区公约,与您携手共创和谐专业的开发者社区。