Java ip地址查询,根据ip接口获得ip所在省市区,邮编,运营商等

早上一来,项目经理就说需要添加一个用户ip归属地查询功能,然后在网上搜罗半天,研究出一个比较简单的方法,通过接口返回地址json数据

有百度接口,新浪接口,这里用的是淘宝ip接口

通过淘宝IP地址库获取IP位置

请求接口(GET):http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]

响应信息:(json格式的)国家 、省(自治区或直辖市)、市(县)、运营商等

2018.2.26运行项目发现淘宝接口报错502,于是找到一个替代的接口,新浪接口

  String sip = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js";

  直接将淘宝接口 换成这个就可以运行,过程一样

2018/6/19 还是用淘宝ip接口

  1 public static void main(String[] args) {
  2          // 测试ip 221.232.245.73 湖北武汉
  3          String ip = "221.232.245.73";
  4          String address = "";
  5          try {
  6            address = addressUtils.getAddresses("ip="+ip, "utf-8");
  7          } catch (UnsupportedEncodingException e) {
  8            // TODO Auto-generated catch block
  9            e.printStackTrace();
 10          }
 11            System.out.println(address);
 12            // 输出结果为:中国 湖北省 武汉市
 13          }
 14 
 15 
 16  
 17      /**  3      * @param content
 18      *   请求的参数 格式为:name=xxx&pwd=xxx
 19      * @param encoding
 20      *   服务器端请求编码。如GBK,UTF-8等
 21      * @return
 22      * @throws UnsupportedEncodingException
 23      */
 24      public String getAddresses(String content, String encodingString) throws UnsupportedEncodingException {
 25          // 这里调用pconline的接口
 26          String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
 27          // 从http://whois.pconline.com.cn取得IP所在的省市区信息
 28          String returnStr = this.getResult(urlStr, content, encodingString);
 29          if (returnStr != null) {
 30              // 处理返回的省市区信息
 31              System.out.println("IP====="+returnStr);
 32              String[] temp = returnStr.split(",");
 33              if(temp.length<3){
 34                  return "0";                                        //无效IP,局域网测试
 35              }
 36              String region = (temp[5].split(":"))[1].replaceAll(""", "");
 37              region = decodeUnicode(region);                        //
 38              System.out.println("region = "+region);
 39              
 40              String country = "";
 41              String area = "";
 42              // String region = "";
 43              String city = "";
 44              String county = "";
 45              String isp = "";
 46              System.out.println("temp的长度="+temp.length);
 47              for (int i = 0; i < temp.length; i++) {
 48                 switch (i) {
 49               如果使用的是新浪的接口,那这里的需要修改,case:3 4 5分别对应国家,省,市区
 50                         case 1:
 51                          country = (temp[i].split(":"))[2].replaceAll(""", "");
 52                          country = decodeUnicode(country);            // 国家
 53                          break;
 54                      case 3:
 55                          area = (temp[i].split(":"))[1].replaceAll(""", "");
 56                          area = decodeUnicode(area);                // 地区 
 57                          break;
 58                      case 5:
 59                           region = (temp[i].split(":"))[1].replaceAll(""", "");
 60                           region = decodeUnicode(region);            // 省份 
 61                           break; 
 62                      case 7:
 63                           city = (temp[i].split(":"))[1].replaceAll(""", "");
 64                           city = decodeUnicode(city);                // 市区
 65                           break; 
 66                      case 9:
 67                            county = (temp[i].split(":"))[1].replaceAll(""", "");
 68                            county = decodeUnicode(county);            // 地区 
 69                            break;
 70                      case 11:
 71                           isp = (temp[i].split(":"))[1].replaceAll(""", "");
 72                           isp = decodeUnicode(isp);                 // ISP公司
 73                           break;
 74                 }
 75            }
 76              System.out.println(country+"="+area+"="+region+"="+city+"="+county+"="+isp);
 77              return region;
 78          }
 79          return null;
 80      }
 81 
 82      
 83      
 84      /**
 85       * @param urlStr
 86       *   请求的地址
 87       * @param content
 88       *   请求的参数 格式为:name=xxx&pwd=xxx
 89       * @param encoding
 90       *   服务器端请求编码。如GBK,UTF-8等
 91       * @return
 92       */
 93       private String getResult(String urlStr, String content, String encoding) {
 94           URL url = null;
 95           HttpURLConnection connection = null;
 96           try {
 97               url = new URL(urlStr);
 98               connection = (HttpURLConnection) url.openConnection(); // 新建连接实例
 99               connection.setConnectTimeout(2000);                     // 设置连接超时时间,单位毫秒
100               connection.setReadTimeout(2000);                        // 设置读取数据超时时间,单位毫秒
101               connection.setDoOutput(true);                           // 是否打开输出流 true|false
102               connection.setDoInput(true);                            // 是否打开输入流true|false
103               connection.setRequestMethod("POST");                    // 提交方法POST|GET
104               connection.setUseCaches(false);                         // 是否缓存true|false
105               connection.connect();                                   // 打开连接端口
106               DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
107               out.writeBytes(content);                                // 写数据,也就是提交你的表单 name=xxx&pwd=xxx
108               out.flush();                                            // 刷新
109               out.close();                                            // 关闭输出流
110               BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据 ,以BufferedReader流来读取
111               StringBuffer buffer = new StringBuffer();
112               String line = "";
113               while ((line = reader.readLine()) != null) {
114                   buffer.append(line);
115               }
116               reader.close();
117               return buffer.toString();
118           } catch (IOException e) {
119               e.printStackTrace();
120           } finally {
121               if (connection != null) {
122                   connection.disconnect();                            // 关闭连接
123               }
124           }
125           return null;
126       }
127 
128       /**
129        * unicode 转换成 中文
130        *
131        * @author fanhui 2007-3-15
132        * @param theString
133        * @return
134        */
135        public static String decodeUnicode(String theString) {
136        char aChar;
137        int len = theString.length();
138        StringBuffer outBuffer = new StringBuffer(len);
139        for (int x = 0; x < len;) {
140            aChar = theString.charAt(x++);
141            if (aChar == '\') {
142                aChar = theString.charAt(x++);
143                    if (aChar == 'u') {
144                        int value = 0;
145                        for (int i = 0; i < 4; i++) {
146                            aChar = theString.charAt(x++);
147                             switch (aChar) {
148                             case '0':
149                             case '1':
150                             case '2':
151                             case '3':
152                             case '4':
153                             case '5':
154                             case '6':
155                             case '7':
156                             case '8':
157                             case '9':
158                             value = (value << 4) + aChar - '0';
159                             break;
160                             case 'a':
161                             case 'b':
162                             case 'c':
163                             case 'd':
164                             case 'e':
165                             case 'f':
166                             value = (value << 4) + 10 + aChar - 'a';
167                             break;
168                             case 'A':
169                             case 'B':
170                             case 'C':
171                             case 'D':
172                             case 'E':
173                             case 'F':
174                             value = (value << 4) + 10 + aChar - 'A';
175                             break;
176                             default:
177                             throw new IllegalArgumentException(
178                              "Malformed  encoding.");
179                             }
180                 }
181                 outBuffer.append((char) value);
182                } else {
183                     if (aChar == 't') {
184                     aChar = '	';
185                     } else if (aChar == 'r') {
186                     aChar = '
';
187                     } else if (aChar == 'n') {
188                     aChar = '
';
189                     } else if (aChar == 'f') {
190                     aChar = 'f';
191                     }
192                 outBuffer.append(aChar);
193                }
194            } else {
195            outBuffer.append(aChar);
196            }
197        }
198            return outBuffer.toString();
199        }

    

输出结果为

IP====={"code":0,
    "data":{
      "ip":"221.232.245.73",   //ip
      "country":"中国",      //国家
      "area":"",          //区
      "region":"湖北",       //省
      "city":"武汉",        //市
      "county":"XX",      
      "isp":"电信",        //宽带运营
      "country_id":"CN",     //国家id
      "area_id":"",        //区编码
      "region_id":"420000",   //省编码
      "city_id":"420100",    //市编码
      "county_id":"xx",     
      "isp_id":"100017"}} region = 武汉 temp的长度=14 中国==武汉=电信==420100
一个95后程序员的自述: 现在的我还年轻,还有激情,要在有限的时间和激情里实现自我价值.
原文地址:https://www.cnblogs.com/zhan1995/p/8384801.html