java 根据ip地址获取地理位置及运营商。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoyanli8077/article/details/88120192

1、基于淘宝API

   /**
     * 根据ip获取城市(运营商)名称
     * @param ip
     * @return
     * @throws Exception
     */
    public static String getLocationByIp(String ip){
        String city ="";
        Map data = null;
        try {
            if(ip.equals("127.0.0.1")) {
                return "本机地址";
            }
            String jsonStr = readJsonFromUrl("http://ip.taobao.com/service/getIpInfo.php?ip="+ip); //淘宝api
            if(MyUtil.isNotEmpty(jsonStr)){
                data = JSONObject.parseObject(jsonStr);
                Map dataInfo =(Map)data.get("data");
                String cityStr = (String)dataInfo.get("city");
                if(cityStr.equals("内网IP")) {
                    city =cityStr;
                }else {
                    city = cityStr +","+(String)dataInfo.get("isp");
                }
                 return city;
            }
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.toString());
            return "未知";
        }
        return city;
    }

    private static String readJsonFromUrl(String url) throws Exception{
        InputStream is = null;
        BufferedReader rd = null;
        String str = "";
        try {
            is = new URL(url).openStream();
            rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            str = readAll(rd);
        }finally {
            //关闭输入流
            if(is != null) {
                is.close();
            }
        }
        return str;
    }
    
    private static String readAll(Reader rd) throws IOException {
       StringBuilder sb = new StringBuilder();
       int cp;
       while ((cp = rd.read()) != -1) {
           sb.append((char) cp);
       }
       return sb.toString();
   }

猜你喜欢

转载自blog.csdn.net/xiaoyanli8077/article/details/88120192