C# 使用 HttpClient 实现天气查询 - 代码示例
使用 HTTP 协议实现天气查询,可以使用 C# 的 HttpClient 类来发送 HTTP 请求并接收响应。以下是一个简单的示例代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string city = '北京'; // 要查询的城市
string apiKey = 'your_api_key'; // 你的天气 API 密钥
// 创建 HttpClient 实例
using (HttpClient client = new HttpClient())
{
try
{
// 发送 GET 请求并获取响应
HttpResponseMessage response = await client.GetAsync($'http://api.weatherapi.com/v1/current.json?key={apiKey}&q={city}');
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
// 处理响应数据
Console.WriteLine(responseBody);
// 可以使用 JSON 解析库(如 Newtonsoft.Json)来解析响应数据
// JObject json = JObject.Parse(responseBody);
// string temperature = (string)json['current']['temp_c'];
// Console.WriteLine($'当前温度:{temperature}°C');
}
catch (HttpRequestException ex)
{
Console.WriteLine($'请求失败:{ex.Message}');
}
}
}
}
请注意,上述代码中的 your_api_key 需要替换为你的天气 API 密钥。你可以在天气 API 提供商的网站上注册并获取密钥。
此示例代码使用的是 WeatherAPI(https://www.weatherapi.com/)提供的天气 API。你可以根据你使用的具体天气 API 进行相应的调整。
原文地址: https://www.cveoy.top/t/topic/pmui 著作权归作者所有。请勿转载和采集!