一个天气接口的封装及使用例子
中国天气网暴露了一些获取天气信息的接口:
http://www.weather.com.cn/data/sk/101010100.html
http://www.weather.com.cn/data/cityinfo/101010100.html
http://m.weather.com.cn/data/101010100.html
这些接口会返回JSON格式的天气数据,我们可以通过解析JSON,获取相应城市的天气数据。
URL中的文件名指代城市的编号,具体的对应关系可以看下边这篇文章,本文源代码中亦有提供。
http://jerryqiu.iteye.com/blog/1106241
有了这些数据,我们就可以通过省和城市的名称查询天气了。
具体思路:
以查询北京天气为例,首先根据“北京”获取城市代码“101010100”,然后拼接查询Url“http://m.weather.com.cn/data/101010100.html”,发送这个Url请求,返回数据:
{"weatherinfo":{"city":"北京","city_en":"beijing","date_y":"2012年5月29日","date":"","week":"星期二","fchh":"11","cityid":"101010100","temp1":"27℃~16℃","temp2":"27℃~15℃","temp3":"29℃~16℃","temp4":"26℃~16℃","temp5":"25℃~15℃","temp6":"27℃~14℃","tempF1":"80.6℉~60.8℉","tempF2":"80.6℉~59℉","tempF3":"84.2℉~60.8℉","tempF4":"78.8℉~60.8℉","tempF5":"77℉~59℉","tempF6":"80.6℉~57.2℉","weather1":"雷阵雨转阴","weather2":"多云转晴","weather3":"晴转多云","weather4":"阴转雷阵雨","weather5":"雷阵雨转多云","weather6":"多云转阴","img1":"4","img2":"2","img3":"1","img4":"0","img5":"0","img6":"1","img7":"2","img8":"4","img9":"4","img10":"1","img11":"1","img12":"2","img_single":"4","img_title1":"雷阵雨","img_title2":"阴","img_title3":"多云","img_title4":"晴","img_title5":"晴","img_title6":"多云","img_title7":"阴","img_title8":"雷阵雨","img_title9":"雷阵雨","img_title10":"多云","img_title11":"多云","img_title12":"阴","img_title_single":"雷阵雨","wind1":"微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"暖","index_d":"较凉爽,建议着长袖衬裤等春秋过渡装。体弱者宜着长袖衬衫和马甲。但昼夜温差较大,请适当增减衣服。","index48":"暖","index48_d":"较凉爽,建议着长袖衬裤等春秋过渡装。体弱者宜着长袖衬衫和马甲。但昼夜温差较大,请适当增减衣服。","index_uv":"弱","index48_uv":"中等","index_xc":"不宜","index_tr":"一般","index_co":"较舒适","st1":"23","st2":"13","st3":"28","st4":"17","st5":"29","st6":"16","index_cl":"较不宜","index_ls":"不宜","index_ag":"较易发"}}
从中获取需要的数据就可以了。这里边的数据很详细,基本可以满足常用的需求了。看我这边显示的效果:
为了实现这个例子,
(1)首先定义了两个资源文件:
WeatherCity.txt 城市名称与代码对应
WeatherProvince.txt 省名称与代码对应,这个是从WeatherCity.txt中提炼出来的。
城市代码的前5位是所属省代码。
(2)根据省名称和城市名称获取城市代码,然后获取城市数据
这样使用中文的省和城市名称就可以快速查询天气信息了。为了更快速的构造请求天气的Url,程序对城市代码数据做了缓存,一共两千多条,存放到一个Dictionary中。
(3)这个例子使用asp.net MVC做的,移植到其它项目也很方便,核心的代码都在(2)中。
本示例中的天气数据都是实时从中国天气网获取的,有时可能速度较慢,您还可以存在本地服务器,然后按照一定的时间规则去更新最新天气情况。
这样就可以随心所欲的定义自己的天气显示方式了。
当然还有一点需要提醒到各位,此方法可以免费获取到天气数据,但是使用这些数据是需要授权的,详细请看:http://service.weather.com.cn/plugin/authorization.shtml。
提供的下载程序完整实现天气接口的封装,并附带一个完全可用的示例。直接运行需要VS2010+ASP.NET MVC 3,您也可以从中获取关键的代码部分加到自己的项目中。