5、HarmonyOS 网络请求实战:请求天气接口并展示图文数据(附实操案例) 原创

wx5eb6c0016c3c7
发布于 2025-5-13 11:08
浏览
0收藏

🧰 一、准备工作

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);
  }
}

该页面在加载时会自动请求天气数据,并展示城市、温度、天气描述及对应图标。


📸 三、效果展示

以下是应用运行后的界面效果截图:

天气应用效果图

图:展示城市天气信息,包括温度、天气描述和图标


🧩 四、扩展建议


📘 总结

通过本篇实战案例,我们学习了如何在 HarmonyOS 中: (【HarmonyOS NEXT】网络请求_鸿蒙网络请求 - CSDN博客)

这些技能对于开发需要与服务器交互的应用至关重要。


©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
收藏
回复
举报
回复
    相关推荐