查询天气在C#中怎么实现
时间: 2024-03-21 14:41:46 浏览: 10
在C#中,查询天气可以通过使用第三方API来实现。常用的天气API有心知天气、百度天气、和风天气等。下面以心知天气API为例,介绍实现方法:
1.注册心知天气账号,获取API key。
2.在C#中使用HttpWebRequest或HttpClient等工具发送HTTP请求,获取天气数据。
3.解析返回的JSON数据,提取所需的天气信息。
以下是一个简单的示例代码:
```csharp
using System;
using System.Net.Http;
using System.Text.Json;
class WeatherQuery
{
static async void GetWeather()
{
string url = "https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
JsonDocument doc = JsonDocument.Parse(responseBody);
JsonElement root = doc.RootElement;
string city = root.GetProperty("results")[0].GetProperty("location").GetProperty("name").GetString();
string weather = root.GetProperty("results")[0].GetProperty("now").GetProperty("text").GetString();
string temperature = root.GetProperty("results")[0].GetProperty("now").GetProperty("temperature").GetString();
Console.WriteLine($"城市:{city},天气:{weather},温度:{temperature}℃");
}
static void Main(string[] args)
{
GetWeather();
Console.ReadKey();
}
}
```
需要将`your_api_key`替换为自己的API key。该代码会查询北京的天气信息,并输出城市、天气、温度。