在现代应用中,获取并展示实时天气信息是常见的功能。本文将通过实战案例,演示如何在 HarmonyOS 中使用原生 HTTP 模块请求天气数据,并将其以图文形式展示。
🧰 一、准备工作
1. 获取天气 API 密钥
注册并登录 和风天气 平台,申请免费 API Key。 (【华为HarmonyOS开发】使用和风天气api开发天气预报项目之主页 ...)
2. 配置网络权限
在 module.json5 文件中添加网络权限: (HarmonyOS 窥探网络请求 - 稀土掘金)
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
确保在 app.json5 中设置允许明文传输(如使用 HTTP): (【HarmonyOS NEXT】网络请求_鸿蒙网络请求 - CSDN博客)
"network": {
"cleartextTraffic": true
}
🛠️ 二、实战开发:构建天气查询页面
1. 创建 HTTP 请求模块
在 model 目录下创建 WeatherService.ets: (Weather Service Kit接口有定位功能吗? - Huawei Developer)
import http from '@ohos.net.http';
export async function fetchWeather(city: string): Promise<any> {
const httpRequest = http.createHttp();
const url = `https://devapi.qweather.com/v7/weather/now?location=${city}&key=YOUR_API_KEY`;
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
},
connectTimeout: 10000,
readTimeout: 10000
});
if (response.responseCode === 200) {
return JSON.parse(response.result.toString());
} else {
console.error('请求失败,状态码:', response.responseCode);
return null;
}
} catch (error) {
console.error('网络请求异常:', error);
return null;
} finally {
httpRequest.destroy();
}
}
请将 YOUR_API_KEY 替换为实际申请的 API 密钥。
2. 创建天气展示页面
在 pages 目录下创建 WeatherPage.ets:
import { fetchWeather } from '../model/WeatherService';
@Entry
@Component
struct WeatherPage {
@State city: string = '北京';
@State temperature: string = '';
@State weatherText: string = '';
@State iconUrl: string = '';
async aboutToAppear() {
const data = await fetchWeather(this.city);
if (data && data.now) {
this.temperature = data.now.temp + '℃';
this.weatherText = data.now.text;
this.iconUrl = `https://api.qweather.com/icons/${data.now.icon}.png`;
}
}
build() {
Column() {
Text(`城市:${this.city}`)
.fontSize(20)
.margin({ bottom: 10 });
Text(`温度:${this.temperature}`)
.fontSize(20)
.margin({ bottom: 10 });
Text(`天气:${this.weatherText}`)
.fontSize(20)
.margin({ bottom: 10 });
Image(this.iconUrl)
.width(100)
.height(100);
}
.padding(20)
.alignItems(HorizontalAlign.Center);
}
}
该页面在加载时会自动请求天气数据,并展示城市、温度、天气描述及对应图标。
📸 三、效果展示
以下是应用运行后的界面效果截图:
图:展示城市天气信息,包括温度、天气描述和图标
🧩 四、扩展建议
- 城市选择功能:添加下拉菜单或搜索框,允许用户选择或输入城市名称。
- 天气预报:集成未来几天的天气预报数据,展示趋势图。
- 多语言支持:根据用户系统语言,展示对应语言的天气信息。 (鸿蒙项目开发天气预报_基于鸿蒙的天气预报设计-CSDN博客)
📘 总结
通过本篇实战案例,我们学习了如何在 HarmonyOS 中: (【HarmonyOS NEXT】网络请求_鸿蒙网络请求 - CSDN博客)
- 配置网络权限;
- 使用原生 HTTP 模块发起网络请求;
- 解析 JSON 数据;
- 动态更新 UI 组件展示数据。 (HarmonyOS 窥探网络请求 - 稀土掘金, 【HarmonyOS NEXT】网络请求_鸿蒙网络请求 - CSDN博客)
这些技能对于开发需要与服务器交互的应用至关重要。