根據IP定位獲取城市代碼


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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM