C# 使用 HttpClient 发送 HTTP POST 请求获取天气数据
使用 C# 的 HttpClient 类发送 HTTP POST 请求获取天气数据,可以方便地从天气 API 获取天气信息。以下是一个示例代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = 'http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=YOUR_LOCATION';
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.PostAsync(url, null);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody); // 输出天气数据
}
catch (HttpRequestException ex)
{
Console.WriteLine($'Error: {ex.Message}');
}
}
}
}
在上述代码中,需要将'YOUR_API_KEY'和'YOUR_LOCATION'替换为实际的天气 API 密钥和要查询的地点。请注意,这只是一个示例代码,实际使用时需要使用合适的天气 API 和参数。
注意:
- 代码中使用的天气 API 仅为示例,实际使用时请根据需要选择合适的 API。
- 需要在天气 API 提供商网站上注册并获取 API 密钥。
- 请参考 API 文档获取正确的 URL 和参数。
原文地址: https://www.cveoy.top/t/topic/pmoY 著作权归作者所有。请勿转载和采集!