• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Neil_Ling

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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

 

posted on 2015-01-31 16:19  Neil_Ling  阅读(5611)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3