
回复
注册并登录 和风天气 平台,申请免费 API Key。 (【华为HarmonyOS开发】使用和风天气api开发天气预报项目之主页 …)
在 module.json5
文件中添加网络权限: (HarmonyOS 窥探网络请求 - 稀土掘金)
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
确保在 app.json5
中设置允许明文传输(如使用 HTTP): (【HarmonyOS NEXT】网络请求_鸿蒙网络请求 - CSDN博客)
"network": {
"cleartextTraffic": true
}
在 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 密钥。
在 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);
}
}
该页面在加载时会自动请求天气数据,并展示城市、温度、天气描述及对应图标。
以下是应用运行后的界面效果截图:
图:展示城市天气信息,包括温度、天气描述和图标
通过本篇实战案例,我们学习了如何在 HarmonyOS 中: (【HarmonyOS NEXT】网络请求_鸿蒙网络请求 - CSDN博客)
这些技能对于开发需要与服务器交互的应用至关重要。