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.JsonNewtonsoft.Json 库。例如:

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

相关推荐
geovindu4 分钟前
go: Broadcast Pattern
开发语言·后端·设计模式·golang·广播模式
sycmancia8 分钟前
Qt——Qt程序打包
开发语言·qt
郝学胜-神的一滴12 分钟前
Qt 高级开发 026:QTabWidget御道,从筑基到化境
开发语言·c++·qt·程序人生·软件构建·用户界面
Jun62616 分钟前
QT(14)-UBUNTU下QT使用串口
开发语言·qt·ubuntu
Jun62616 分钟前
QT(16)-云端版本管理
开发语言·qt
ggaofeng17 分钟前
试用zeroclaw
java·开发语言
~|Bernard|29 分钟前
关于go语言中二维切片的append操作陷阱
开发语言·后端·golang
c++之路32 分钟前
C/C++ 全链路编译工具汇总
c语言·开发语言·c++
cici1587432 分钟前
C# LAS 点云读取与处理工具
stm32·单片机·c#
c2385633 分钟前
C++的IO流深入理解(下)
开发语言·c++