本文從http://m.weather.com.cn/獲取天氣信息掷漱。
獲取城市編號(hào)
一級(jí)城市列表:
-
數(shù)據(jù)源:
-
得到的數(shù)據(jù):
01|北京,02|上海,03|天津,04|重慶,05|黑龍江,06|吉林,07|遼寧,08|內(nèi)蒙古,09|河北,10|山西,11|陜西,12|山東,13|新疆,14|西藏,15|青海,16|甘肅,17|寧夏,18|河南,19|江蘇,20|湖北,21|浙江,22|安徽,23|福建,24|江西,25|湖南,26|貴州,27|四川,28|廣東,29|云南,30|廣西,31|海南,32|香港,33|澳門,34|臺(tái)灣
二級(jí)城市列表
-
數(shù)據(jù)源,例如廣東
-
得到的數(shù)據(jù)
2801|廣州,2802|韶關(guān),2803|惠州,2804|梅州,2805|汕頭,2806|深圳,2807|珠海,2808|佛山,2809|肇慶,2810|湛江,2811|江門,2812|河源,2813|清遠(yuǎn),2814|云浮,2815|潮州,2816|東莞,2817|中山,2818|陽(yáng)江,2819|揭陽(yáng),2820|茂名,2821|汕尾
三級(jí)城市列表榄檬,
-
數(shù)據(jù)源卜范,例如深圳2806
-
得到的數(shù)據(jù):
280601|深圳
由城市三級(jí)碼得到城市編碼
-
數(shù)據(jù)源,如河北.唐山.遷西(ps 哪里的板栗很出名哦)
-
城市編碼:
090507|101090507
則河北.唐山.遷西的城市編碼為101090507
獲取城市天氣
- 今日及未來天氣接口【內(nèi)容最詳細(xì)】
接口已經(jīng)停用了鹿榜,http://m.weather.com.cn/data/101090507.html海雪,需要使用新接口锦爵。
有一個(gè)新的接口可以使用,不過使用前需要注冊(cè)奥裸,
得到數(shù)據(jù)
{"weatherinfo":{"city":"遷西","cityid":"101090507","temp1":"16℃","temp2":"1℃","weather":"多云","img1":"d1.gif","img2":"n1.gif","ptime":"08:00"}}
相關(guān)代碼
從Web獲取json
String src ="http://www.weather.com.cn/data/cityinfo/101090507.html";
String getJson(String src) {
try {
URL url = new URL(src);
int lineIndex=0;
HttpURLConnection httpConnect = (HttpURLConnection) url.openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(httpConnect.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line ="";
String jsonStr = "";
while((line = bufferedReader.readLine())!=null){
lineIndex++;
jsonStr += line;
}
Log.e(TAG, jsonStr);
return jsonStr;
} catch (IOException e){
e.printStackTrace();
}
return "";
}
此段代碼的返回值险掀,即是json格式的天氣信息。
解析json湾宙,獲得想要信息
String getWeatherInfo(String json){
String weatherInfo ="";
try{
String filed ="";
JSONObject obj = new JSONObject(json);
filed = obj.getString("weatherinfo");
JSONObject objsub=new JSONObject(filed);
weatherInfo+="深圳 ,";
weatherInfo += objsub.getString("temp1") + "--";
weatherInfo += objsub.getString("temp2") + ", ";
weatherInfo += objsub.get("weather");
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG,weatherInfo);
return weatherInfo;
}