2023-12-25
•
0k
1. 天气查询功能介绍 天气查询API在现代Web和移动应用中扮演着重要角色,它可以为用户提供实时天气数据、未来天气预报以及生活指数等关键信息。本文将详细介绍如何实现一个高效、稳定的天气查询服务,涵盖从API选择、异步编程实现到缓存优化的完整开发流程。
2. 天气API服务选择指南 在开发天气查询应用时,选择合适的API服务提供商至关重要。以下是几个主流的天气API服务对比:
和风天气API:国内数据覆盖全面,API文档完善,适合后端开发使用 OpenWeatherMap:全球天气数据服务,国际化支持好 高德地图天气API:国内覆盖较全面,适合本地化应用 百度地图天气API:与百度地图集成良好,适合地图应用场景 本文以和风天气API为例,详细讲解调用天气API的完整实现方案,包括API密钥获取、请求构建、响应解析和错误处理等关键环节。
3. 天气查询API代码实现 3.1 获取和风天气API密钥 在开始天气查询开发前,首先需要在和风天气开发者平台注册账号并获取API密钥。注册流程简单,完成后即可获得免费额度的API访问权限。
3.2 天气查询类实现 using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; public class WeatherAPI { private readonly string _apiKey; private readonly string _baseUrl; private readonly HttpClient _httpClient; public WeatherAPI(string apiKey) { _apiKey = apiKey; _baseUrl = "https://devapi.qweather.com/v7"; _httpClient = new HttpClient(); _httpClient.Timeout = TimeSpan.FromSeconds(10); } /// <summary> /// 实现获取指定位置的实时天气数据 /// 支持城市ID或经纬度查询 /// </summary> public async Task<Dictionary<string, object>> GetCurrentWeatherAsync(string location) { string url = $"{_baseUrl}/weather/now"; var parameters = new Dictionary<string, string> { { "key", _apiKey }, { "location", location } // 可以是城市ID或经纬度 }; try { using (var response = await _httpClient.GetAsync($"{url}?{BuildQueryString(parameters)}")) { response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(responseBody); if (data.code == "200") { return data.now.ToObject<Dictionary<string, object>>(); } else { Console.WriteLine($"查询失败: {data.code} - {data.msg}"); return null; } } } catch (Exception ex) { Console.WriteLine($"请求异常: {ex.Message}"); return null; } } /// <summary> ///实现获取指定位置的天气预报数据 /// 支持3天或7天预报查询 /// </summary> public async Task<List<Dictionary<string, object>>> GetWeatherForecastAsync(string location, int days = 3) { string url = days <= 3 ? $"{_baseUrl}/weather/3d" : $"{_baseUrl}/weather/7d"; var parameters = new Dictionary<string, string> { { "key", _apiKey }, { "location", location } }; try { using (var response = await _httpClient.GetAsync($"{url}?{BuildQueryString(parameters)}")) { response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(responseBody); if (data.code == "200") { var dailyList = data.daily.ToObject<List<Dictionary<string, object>>>(); return dailyList.GetRange(0, Math.Min(days, dailyList.Count)); } else { Console.WriteLine($"查询失败: {data.code} - {data.msg}"); return new List<Dictionary<string, object>>(); } } } catch (Exception ex) { Console.WriteLine($"请求异常: {ex.Message}"); return new List<Dictionary<string, object>>(); } } /// <summary> ///实现获取指定位置的生活指数数据 /// 包括穿衣、洗车、紫外线、运动、旅游指数 /// </summary> public async Task<List<Dictionary<string, object>>> GetLifeIndexAsync(string location) { string url = $"{_baseUrl}/indices/1d"; var parameters = new Dictionary<string, string> { { "key", _apiKey }, { "location", location }, { "type", "1,2,3,5,9" } // 包括穿衣、洗车、紫外线、运动、旅游指数 }; try { using (var response = await _httpClient.GetAsync($"{url}?{BuildQueryString(parameters)}")) { response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(responseBody); if (data.code == "200") { return data.daily.ToObject<List<Dictionary<string, object>>>(); } else { Console.WriteLine($"查询失败: {data.code} - {data.msg}"); return new List<Dictionary<string, object>>(); } } } catch (Exception ex) { Console.WriteLine($"请求异常: {ex.Message}"); return new List<Dictionary<string, object>>(); } } /// <summary> /// 构建查询字符串 /// </summary> private string BuildQueryString(Dictionary<string, string> parameters) { var queryParts = new List<string>(); foreach (var param in parameters) { queryParts.Add($"{param.Key}={System.Net.WebUtility.UrlEncode(param.Value)}"); } return string.Join("&", queryParts); } } 3.3天气查询实例代码示例 // 使用示例 class Program { static async Task Main(string[] args) { // 替换为您的API密钥 string apiKey = "your_api_key_here"; var weatherAPI = new WeatherAPI(apiKey); // 查询北京天气(使用城市ID) string location = "101010100"; // 北京的城市ID // 获取实时天气 var currentWeather = await weatherAPI.GetCurrentWeatherAsync(location); if (currentWeather != null) { Console.WriteLine("实时天气:"); Console.WriteLine($"温度: {currentWeather["temp"]}°C"); Console.WriteLine($"天气: {currentWeather["text"]}"); Console.WriteLine($"风向: {currentWeather["windDir"]} {currentWeather["windScale"]}级"); Console.WriteLine($"湿度: {currentWeather["humidity"]}%"); } // 获取3天预报 var forecast = await weatherAPI.GetWeatherForecastAsync(location); Console.WriteLine("\n未来3天预报:"); foreach (var day in forecast) { Console.WriteLine($"日期: {day["fxDate"]}"); Console.WriteLine($"天气: {day["textDay"]} -> {day["textNight"]}"); Console.WriteLine($"温度: {day["tempMin"]}°C - {day["tempMax"]}°C"); Console.WriteLine(); } // 获取生活指数 var lifeIndices = await weatherAPI.GetLifeIndexAsync(location); Console.WriteLine("\n生活指数:"); foreach (var index in lifeIndices) { Console.WriteLine($"{index["name"]}: {index["level"]} - {index["text"]}"); } } } 4. ASP.NET Core天气查询Web API服务实现 以下是使用ASP.NET Core框架构建高性能天气查询Web API服务的完整实现,支持跨平台部署和高并发访问: