基于各种强大的因素影响,我们在使用Google的天气预报会发生神奇的事件,故本例子利用中国天气网的接口,读者可登陆http://wishblog.sinaapp.com/378了解
//传入地址,获取网页信息
String str = getHtml("http://m.weather.com.cn/data/101280101.html");
其中101280101是城市代码,此处以广州为例,其他情况,可登陆http://wishblog.sinaapp.com/378了解
public static byte[] readStream(InputStream inputStream) throws Exception {
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
inputStream.close();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
public static String getHtml(String urlpath) throws Exception {
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
byte[] data = readStream(inputStream);
String html = new String(data);
return html;
}
return null;
}
以下是http://m.weather.com.cn/data/101280101.html可以提取的信息
{"weatherinfo":{"city":"广州","city_en":"guangzhou","date_y":"2013年1月17日","date":"","week":"星期四","fchh":"18","cityid":"101280101","temp1":"8℃~16℃","temp2":"6℃~18℃","temp3":"11℃~20℃","temp4":"15℃~22℃","temp5":"14℃~21℃","temp6":"13℃~19℃","tempF1":"46.4℉~60.8℉","tempF2":"42.8℉~64.4℉","tempF3":"51.8℉~68℉","tempF4":"59℉~71.6℉","tempF5":"57.2℉~69.8℉","tempF6":"55.4℉~66.2℉","weather1":"晴","weather2":"晴","weather3":"多云","weather4":"阴","weather5":"多云","weather6":"阴","img1":"0","img2":"99","img3":"0","img4":"99","img5":"1","img6":"99","img7":"2","img8":"99","img9":"1","img10":"99","img11":"2","img12":"99","img_single":"0","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":"北风3-4级","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"3-4级","fl6":"小于3级","index":"温凉","index_d":"建议着夹衣加薄羊毛衫等春秋服装。体弱者宜着夹衣加羊毛衫。但昼夜温差较大,注意增减衣服。","index48":"舒适","index48_d":"建议着薄型套装或牛仔衫裤等春秋过渡装。年老体弱者宜着套装、夹克衫等。","index_uv":"中等","index48_uv":"中等","index_xc":"适宜","index_tr":"适宜","index_co":"舒适","st1":"16","st2":"8","st3":"17","st4":"7","st5":"20","st6":"12","index_cl":"适宜","index_ls":"适宜","index_ag":"极不易发"}}
分析数据可发现可获取信息可由JSON进行解析
JSONObject jsonObj = new JSONObject(strResult).getJSONObject("weatherinfo");
//城市名
String cityName = jsonObj.getString("city");
//日期
String date = jsonObj.getString("date_y");
//星期几
String week = jsonObj.getString("week");
//今天天气
String temp1 = jsonObj.getString("temp1");
//明天天气
String temp2 = jsonObj.getString("temp2");
//后天天气
String temp3 = jsonObj.getString("temp3");
//以此类推
至此,利用该接口实现的天气信息的获取,主要代码如上已实现