public String getCityID() throws IOException{ URL url = new URL("http://61.4.185.48:81/g/"); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); // 獲取連接 InputStream is = urlcon.getInputStream(); BufferedReader buffer = new BufferedReader(new InputStreamReader(is)); StringBuffer bs = new StringBuffer(); String l = null; while ((l = buffer.readLine()) != null) { bs.append(l); } String getStr = bs.toString(); System.out.println(getStr); // var ip="121.33.190.178";var id=101280101;if(typeof(id_callback)!="undefined"){id_callback();} // 獲取var id=后面的城市ID String cityID= getStr.substring(getStr.indexOf("id=") + 3, getStr.indexOf(";if")); return cityID; }
我們在瀏覽器輸入
http://61.4.185.48:81/g/可以得到以下信息:
var ip="你當前外網IP";var id=101280101;if(typeof(id_callback)!="undefined"){id_callback();}
上述程序就是將“101280101”這個城市代碼解析出來。
附:
中國天氣網API:http://www.weather.com.cn/data/sk/101110101.html(其中101110101是城市代碼)----->可行
http://www.weather.com.cn/data/cityinfo/101010100.html---------->可行
http://m.weather.com.cn/data/101110101.html(網頁上顯示的是JSON數據,但控制台打印輸出不是JSON數據)
try{ URL url = new URL("http://www.weather.com.cn/data/sk/101110101.html"); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//轉碼。 String line = null; while ((line = reader.readLine()) != null) strBuf.append(line + " "); reader.close(); }catch(MalformedURLException e) { e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } String strJson= strBuf.toString();