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

JAVA学习网 2018-01-31 06:43:01

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

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

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

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

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

    public static void main(String[] args) {
         // 测试ip 221.232.245.73 湖北武汉
         String ip = "221.232.245.73";
         String address = "";
         try {
         address = addressUtils.getAddresses("ip="+ip, "utf-8");
         } catch (UnsupportedEncodingException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
         System.out.println(address);
         // 输出结果为:中国 湖北省 武汉市
         }


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

输出结果为

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

 

阅读(756) 评论(0)