首页 全国天气预报 全国天气预报示例代码 天气预报查询[C#]

天气预报查询示例代码C#

作者: 阅读数:1140 上传时间:2025-04-01

天气预报查询

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

//await Weather.QueryAsync("杭州");
class Weather
{
    // 替换成你的AppKey
    private const string AppKey = "YOUR_APPKEY_HERE";

    public static async Task QueryAsync(string city, int cityid=0, string citycode="", string location="", string ip="")
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                // 构造请求URL
                string url = $"https://api.jisuapi.com/weather/query?appkey={AppKey}&"+;
							$"city={Uri.EscapeDataString(city)}&" +
							$"ip={Uri.EscapeDataString(ip)}&" +
                            $"location={Uri.EscapeDataString(location)}";

                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(url);
                
                // 确保成功响应
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                JObject result = JObject.Parse(responseBody);

                // 处理API返回状态
                if ((int)result["status"] == 0)
                {
                    // 解析信息
					JToken data = result["result"];	
                    Console.WriteLine($"城市:{data["city"]} 日期:{data["date"]} 天气:{data["weather"]} 温度:{data["temp"]} 最高温度:{data["temphigh"]}");
                    Console.WriteLine("未来天气:");
                    foreach (var item in data["daily"])
                    {
                        Console.WriteLine($"{item["date"]} {item["week"]} {item["sunrise"]} {item["sunset"]}");
                    }
					
					Console.WriteLine("未来24小时:");
                    foreach (var item in data["hourly"])
                    {
                        Console.WriteLine($"{item["time"]} {item["weather"]} {item["temp"]} {item["img"]}");
                    }
					
					Console.WriteLine("生活指数:");
                    foreach (var item in data["index"])
                    {
                        Console.WriteLine($"{item["iname"]} {item["ivalue"]} {item["detail"]}");
                    }
					
					Console.WriteLine("空气质量指数:");
					aqi = data["aqi"]
                    Console.WriteLine($"{aqi["aqi"]} {aqi["primarypollutant"]} {aqi["quality"]} {aqi["timepoint"]}");
                }
                else
                {
                    Console.WriteLine($"查询失败:{result["status"]} {result["msg"]}");
                }
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求异常:{ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误:{ex.Message}");
        }
    }
	
	static async Task Main(string[] args)
    {
        //await QueryAsync();
    }
}