首页 > 技术文章 > 根据IP定位获取城市代码

NeilLing 2015-01-31 16:19 原文

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

 

推荐阅读