查询天气在C#中怎么实现简单事例
时间: 2024-04-03 13:34:41 浏览: 11
以下是一个简单的C#控制台应用程序,使用心知天气API查询指定城市的天气信息,并将结果输出到控制台:
```csharp
using System;
using System.Net.Http;
using System.Text.Json;
class Program
{
static async void QueryWeather(string city)
{
// 构造API请求URL
string apiKey = "your_api_key"; // 请替换为自己的API Key
string apiUrl = $"https://api.seniverse.com/v3/weather/now.json?key={apiKey}&location={city}&language=zh-Hans&unit=c";
// 发送HTTP请求
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(apiUrl);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// 解析JSON数据
JsonDocument doc = JsonDocument.Parse(responseBody);
JsonElement root = doc.RootElement;
string cityName = root.GetProperty("results")[0].GetProperty("location").GetProperty("name").GetString();
string temperature = root.GetProperty("results")[0].GetProperty("now").GetProperty("temperature").GetString();
string weather = root.GetProperty("results")[0].GetProperty("now").GetProperty("text").GetString();
// 输出结果
Console.WriteLine($"城市:{cityName},天气:{weather},温度:{temperature}℃");
}
static void Main(string[] args)
{
// 查询北京的天气
QueryWeather("beijing");
// 查询上海的天气
QueryWeather("shanghai");
// 等待用户按下任意键退出程序
Console.ReadKey();
}
}
```
在程序中,我们首先构造了心知天气API的请求URL,然后使用HttpClient发送HTTP请求获取天气数据。接着,我们解析返回的JSON数据,提取出城市名、温度和天气信息,并将结果输出到控制台。
需要注意的是,上述代码中的`your_api_key`需要替换为自己的API Key。