C# 使用 HTTP POST 获取天气数据 - 示例代码

本文提供一个使用 C# 通过 HTTP POST 协议获取天气数据的示例代码。

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            // 设置请求参数
            var parameters = new Dictionary<string, string>
            {
                { 'key', 'your_api_key' }, // 替换为你的 API Key
                { 'city', 'beijing' } // 替换为你要查询的城市
            };

            // 发送 POST 请求
            var response = await client.PostAsync('http://api.weather.com/weather', new FormUrlEncodedContent(parameters));

            // 获取响应内容
            var result = await response.Content.ReadAsStringAsync();

            // 处理响应结果
            Console.WriteLine(result);
        }
    }
}

上述代码中,我们使用 HttpClient 类发送一个 POST 请求到天气查询 API,并将 API Key 和城市作为请求参数传递。然后,我们通过 ReadAsStringAsync 方法获取响应内容,并进行处理。

请注意,需要将 your_api_key 替换为你的 API Key,并将 beijing 替换为你要查询的城市。


原文地址: https://www.cveoy.top/t/topic/pmoR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录