C#中通过get请求获取api.open-meteo.com网站的天气数据

继C++中使用cpp-httplib和nlohmann_json库实现http请求获取天气数据和Nodejs通过get请求获取api.open-meteo.com网站的天气数据、使用Java通过get请求获取api.open-meteo.com网站的天气数据、Python中通过get请求获取api.open-meteo.com网站的天气数据,我们再使用C#语言实现对应功能。

以下是使用 C# 发送 HTTP GET 请求以获取 api.open-meteo.com 网站天气数据的示例代码:


示例代码

csharp 复制代码
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // API URL
        string url = "http://api.open-meteo.com/v1/forecast";
        string latitude = "37.8136";  // 纬度
        string longitude = "144.9631";  // 经度

        // 构造查询参数
        string query = $"?latitude={latitude}&longitude={longitude}&current_weather=true";

        try
        {
            // 使用 HttpClient 发送 GET 请求
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url + query);

                // 检查响应状态码
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseData = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Weather Data:");
                    Console.WriteLine(responseData);
                }
                else
                {
                    Console.WriteLine($"Failed to retrieve data. Status code: {response.StatusCode}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

说明

  1. HttpClient:

    • 使用 HttpClient 类发送 HTTP GET 请求。
    • GetAsync 方法用于异步发送 GET 请求。
  2. API URL 和查询参数:

    • 基础 URL 为 http://api.open-meteo.com/v1/forecast。
    • 查询参数包括:
      • latitude:纬度。
      • longitude:经度。
      • current_weather=true:请求当前天气数据。
  3. 响应处理:

    • 使用 response.IsSuccessStatusCode 检查响应是否成功。
    • 使用 response.Content.ReadAsStringAsync() 异步读取响应内容。
  4. 异常处理:

    • 捕获网络错误或其他异常,并打印错误信息。

运行代码

  1. 创建项目

    在终端中运行以下命令创建一个新的 C# 控制台项目:

    bash 复制代码
    dotnet new console -n GetWeatherData
    cd GetWeatherData
  2. 替换代码

    将上述代码粘贴到 Program.cs 文件中。

  3. 运行程序

    在终端中运行以下命令:

    bash 复制代码
    dotnet run

示例输出

plaintext 复制代码
Weather Data:
{
    "latitude": 37.8136,
    "longitude": 144.9631,
    "generationtime_ms": 0.123,
    "utc_offset_seconds": 0,
    "timezone": "GMT",
    "current_weather": {
        "temperature": 20.5,
        "windspeed": 5.2,
        "winddirection": 180
    }
}

注意事项

  1. 确保你的网络可以访问 http://api.open-meteo.com。

  2. 如果需要解析 JSON 响应,可以使用 System.Text.Json 或 Newtonsoft.Json 库。例如:

    csharp 复制代码
    var weatherData = JsonSerializer.Deserialize<WeatherResponse>(responseData);
    Console.WriteLine($"Temperature: {weatherData.CurrentWeather.Temperature}");
  3. 如果需要更复杂的功能(如 POST 请求或认证),可以扩展代码。

相关推荐
吃我一窝jio1 天前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw1 天前
C++ union 的一种妙用法
开发语言·c++
何以解忧唯有撸码1 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
starzy19901 天前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
布莱克6051 天前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
敲上瘾1 天前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
联犀1 天前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
lcj25112 天前
[C++] C++11
开发语言·c++·笔记
Evand J2 天前
【MATLAB例程】基于IMM-CKF的AOA+测距融合的二维移动目标跟踪定位
开发语言·matlab·目标跟踪
JianZhen✓2 天前
IM 聊天列表为什么总“消息乱跳“:有序插入、时间轴派生、本地截断、已读回执
开发语言·前端·php