现在的位置: 首页 > 综合 > 正文

天气预报API总结

2013年09月27日 ⁄ 综合 ⁄ 共 1713字 ⁄ 字号 评论关闭

 

这里只总结我这次用到的“中国天气网”的天气预报API:

只要发http请求给这个URL就可收到天气数据:http://www.weather.com.cn/data/cityinfo/101010100.html

URL中的 101010100 是北京的id,其他城市的id可以在中国天气网上查到。余下的工作就是将天气数据按照自己的方式显示出来。

收到的数据是JSON格式的,JSON是一种网页交换数据的格式,可以参考http://www.json.org/,上面有很多parser:https://github.com/udp/json-parser

JSON数据是以key-value的形式来显示的,如下是收到的json数据:

{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"1℃","temp2":"-5℃","weather":"阴转多云","img1":"d2.gif","img2":"n1.gif","ptime":"11:00"}}

解析出来就可以显示了,要注意数据过来的时候是UTF8的,还要转成unicode才能显示。对于图片的话,就直接到天气网上“图片另存为”就可以拿下来预先保存好,等收到天气数据的时候去拿对应的图片去显示就行,这样既节省流量也节省code。

需要注意的是如果我们指定Socket Connection的 keep-alive(永久链接)的话,收到数据的thansfer-encoding是trunked,没有content-length这个字段,所以不能依赖content-length来决定自己的buffer要预留多少。

如下是通过mozilla获取天气信息,通过ethreal抓到的发出去的包。

如下是收到的包。

因为还没有解决UTF8转anscii的问题,所以目前只能显示点临时数据了。发图纪念一下,在 finsh下输入command: screen_capture("/SD/screen.bmp")然后回车就可以抓当前显示的screen的样子下来。

Weather APP跑起来之后的log:

8\ | /
- RT -    hread Operating System
 / | \     1.1.0 build Dec  1 2011
 2006 - 2012 Copyright by rt-thread team
TCP/IP initialized!
W25Q64BV or W25Q64CV detection
finsh />error detected and set to -2/0 (cmd = 5),0x00000004
SD card capacity 7879680 KB
found part[0], begin: 4194304, size: 7.523GB
flash0 mount to / 
sd0 mount to /SD 
stat -> stopped
open url: http://www.weather.com.cn/data/cityinfo/101270101.html
setup_load
total 163 bytes
key = weatherinfokey = cityvalue=: '鎴愰兘'
key = cityidvalue=: '101270101'
key = temp1value=: '12鈩

                         key = temp2value=: '4鈩

                                                 key = weathervalue=: '澶氫簯'
key = img1value=: 'd1.gif'
key = img2value=: 'n1.gif'
key = ptimevalue=: '11:00'
JSON_parser_error: parse failed
pic fn: /SD/weather/Sunny.bmp
99%pic fn: /SD/weather/Sunny.bmp

抱歉!评论已关闭.