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 请求或认证),可以扩展代码。

相关推荐
hehelm39 分钟前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
吴可可1232 小时前
C#AutoCAD二次开发打断多段线
c#
行思理2 小时前
微信支付“商家转账用户确认模式”,新手教程
java·开发语言·微信
麻瓜老宋3 小时前
AI开发C语言应用按步走,表达式计算器calc的第一步,中缀表达式词法分析
c语言·开发语言·atomcode
灯澜忆梦4 小时前
GO_文件处理---字符串操作
开发语言·golang
-银雾鸢尾-4 小时前
里氏替换原则
开发语言·c#·里氏替换原则
এ慕ོ冬℘゜4 小时前
JavaScript 数组核心方法实战|新增元素 + 数组转字符串 零基础详解
开发语言·javascript·ecmascript
一个初入编程的小白4 小时前
C语言:函数栈帧与销毁
c语言·开发语言
czhc11400756634 小时前
718:public internl class;partial []
开发语言
临床数据科学和人工智能兴趣组4 小时前
R语言因其强大的统计功能、灵活的编程环境、活跃的社区支持和强大的R扩展包,迅速成为统计学和数据科学领域的首选工具之一
开发语言·数据分析·r语言·r语言-4.2.1