之前做网站的时候,有个需求获取实时天气相关信息,找了一些开放免费的接口,过了几周发现大数据推了好多类似的帖子(真怪,需要你的时候你不来,很气,拿小本本记下了)
首先里一下思路,获取天气有哪些种方式。我在查阅资料的过程中,找到了两种相对比较友好的(对应以下两个接口网站)。
经纬度获取 和风天气
优点:位置准确,官方api 文档很细,接口丰富,有商业需求可支持定制,用户每天免费 5000次
缺点:收费
城市编码 中国气象局
优点:免费
缺点:都免费了,要撒自行车,硬要说的话 可能不能精准定位(没仔细研究还有没有其他方式获取天气)
-
两者网站接口对比 演示(城市暂定武汉)
经纬度 30.58N, 114.30E
https://devapi.qweather.com/v7/weather/now?location=114.30,30.58&key=cd19b9cc50494568b0d791a66e67f1e5
具体参数参照官方文档 doc
{
"code": "200",
"updateTime": "2023-05-24T10:27+08:00",
"fxLink": "https://www.qweather.com/weather/jiang'an-101200107.html",
"now": {
"obsTime": "2023-05-24T10:12+08:00",
"temp": "19",
"feelsLike": "18",
"icon": "104",
"text": "阴",
"wind360": "271",
"windDir": "西风",
"windScale": "1",
"windSpeed": "2",
"humidity": "80",
"precip": "0.0",
"pressure": "1009",
"vis": "8",
"cloud": "91",
"dew": "15"
},
"refer": {
"sources": ["QWeather", "NMC", "ECMWF"],
"license": ["CC BY-SA 4.0"]
}
}
城市编码 57494
https://weather.cma.cn/api/now/57494
{
"msg": "success",
"code": 0,
"data": {
"location": {
"id": "57494",
"name": "武汉",
"path": "中国, 湖北, 武汉"
},
"now": {
"precipitation": 0.0,
"temperature": 20.9,
"pressure": 1009.0,
"humidity": 71.0,
"windDirection": "西北风",
"windDirectionDegree": 274.0,
"windSpeed": 3.1,
"windScale": "微风"
},
"alarm": [],
"lastUpdate": "2023/05/24 10:25"
}
} -
.net 6.0 代码实现
天气帮助类
public class WeatherHelper
{
///
/// 城市编码获取
///
///
public static async TaskgetWeather(string citycode)
{
//武汉
string url = $"https://weather.cma.cn/api/now/{citycode}";
var res = await $"{url}".GetStringAsync();
JObject jsonObj = JObject.Parse(res);
var weather = jsonObj["data"]["now"].ToString();//输出 "深圳"
return weather;
}///
/// 根据经纬度获取
///
///
public static async TaskgetWeather(float lon, float lat,string key)
{
//api 帮助文档 https://www.qweather.com/
string url = $"https://devapi.qweather.com/v7/weather/now?location={lon},{lat}&key={key}";
var res = $"{url}".GetStringAsync();
JObject jsonObj = JObject.Parse(res.Result);
//key 可能会过期,每个用户每天上限5000次
if (jsonObj["code"].ToString() == "200")
{
result = jsonObj;
break;
}
var weather = result["now"].ToString();
return weather;
}
}