时间:2024-10-12 09:34
人气:
作者:admin
编辑一个实体类,该实体类用于存储获取ip地址的经纬度数据使用
继续编辑三个类,用来存储对应经纬度的具体天气数据包:
改造默认的天气控制器,里面写成我们自己的。例如先写个获取IP的经纬度坐标的请求
运行一下,看下现在的效果,可以看到获取到ip的具体信息,包括运营商、经纬度坐标等。
继续拓展内容,根据经纬度获取天气数据
运行,可以看到一些天气信息
以下是返回的具体json报文,供参考:
{ "latitude": 22.5, "longitude": 114, "generationtime_ms": 0.05698204040527344, "utc_offset_seconds": 0, "timezone": "GMT", "timezone_abbreviation": "GMT", "elevation": 37, "current_weather_units": { "time": "iso8601", "interval": "seconds", "temperature": "°C", "windspeed": "km/h", "winddirection": "°", "is_day": "", "weathercode": "wmo code" }, "current_weather": { "time": "2024-10-11T09:45", "interval": 900, "temperature": 26.1, "windspeed": 6.6, "winddirection": 131, "is_day": 1, "weathercode": 2 } }
数据字段解析 基本信息
LocationInfo locationInfo = null; using (var httpClient = _httpClientFactory.CreateClient()) { httpClient.Timeout = TimeSpan.FromSeconds(100); var res = httpClient.GetAsync("http://ip-api.com/json/").GetAwaiter().GetResult(); res.EnsureSuccessStatusCode(); var location = res.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (!string.IsNullOrEmpty(location)) { locationInfo = JsonConvert.DeserializeObject<LocationInfo>(location); } } if (locationInfo != null) { using (var httpClient = _httpClientFactory.CreateClient()) { httpClient.Timeout = TimeSpan.FromSeconds(100); var res = httpClient.GetAsync($"https://api.open-meteo.com/v1/forecast?latitude={locationInfo.lat}&longitude={locationInfo.lon}¤t_weather=true").GetAwaiter().GetResult(); res.EnsureSuccessStatusCode(); var weather = res.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (!string.IsNullOrEmpty(weather)) { WeatherResponse weatherInfo = JsonConvert.DeserializeObject<WeatherResponse>(weather); return Ok(weatherInfo); } } }
如果需要完整源码,可以在公众号【Dotnet Dancer】内回复“天气查询”即可获取源码地址。

以上就是本文章全部内容,如果有帮助,欢迎点赞、在看、转发分享或评论,谢谢大佬们捧场~
本文作者:Wesky
微信号:WeskyNet001
公众号:Dotnet Dancer
文章链接:https://www.cnblogs.com/weskynet/p/18459831
欢迎扫一扫关注公众号,发现更多其他技术分享