Java ip address query, according to the ip interface to obtain the province, city, zip code, operator, etc

Keywords: Java encoding JSON PHP

In the morning, the project manager said that it is necessary to add a user ip home location query function, and then search the Internet for half a day, and work out a relatively simple method to return address json data through the interface

Baidu interface, Sina interface, Taobao ip interface is used here

Get IP location through Taobao IP address Library

GET: http://ip.taobao.com/service/getIpInfo.php?ip=[ip address string]

Response information: (json format) country, province (autonomous region or municipality directly under the central government), city (county), operator, etc

    public static void main(String[] args) {
         // test ip 221.232.245.73 Wuhan, Hubei
         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);
         // Output: Wuhan City, Hubei Province, China
         }


 
     /**  3      * @param content
  4      *   The requested parameter format is: name = XXX & PWD = XXX
  5      * @param encoding
  6      *   Server side request encoding. Such as GBK,UTF-8, etc
  7      * @return
  8      * @throws UnsupportedEncodingException
  9      */
 10      public String getAddresses(String content, String encodingString) throws UnsupportedEncodingException {
 11          // Call here pconline Interface of
 12          String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
 13          // from http://whois.pconline.com.cn Obtain IP Information of province and city
 14          String returnStr = this.getResult(urlStr, content, encodingString);
 15          if (returnStr != null) {
 16              // Processing returned provincial and city information
 17              System.out.println("IP====="+returnStr);
 18              String[] temp = returnStr.split(",");
 19              if(temp.length<3){
 20                  return "0";                                        //invalid IP,LAN test
 21              }
 22              String region = (temp[5].split(":"))[1].replaceAll("\"", "");
 23              region = decodeUnicode(region);                        // province
 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 Length of="+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);            // Country
 38                          break;
 39                      case 3:
 40                          area = (temp[i].split(":"))[1].replaceAll("\"", "");
 41                          area = decodeUnicode(area);                // region 
 42                          break;
 43                      case 5:
 44                           region = (temp[i].split(":"))[1].replaceAll("\"", "");
 45                           region = decodeUnicode(region);            // Province 
 46                           break; 
 47                      case 7:
 48                           city = (temp[i].split(":"))[1].replaceAll("\"", "");
 49                           city = decodeUnicode(city);                // urban district
 50                           break; 
 51                      case 9:
 52                            county = (temp[i].split(":"))[1].replaceAll("\"", "");
 53                            county = decodeUnicode(county);            // region 
 54                            break;
 55                      case 11:
 56                           isp = (temp[i].split(":"))[1].replaceAll("\"", "");
 57                           isp = decodeUnicode(isp);                 // ISP company
 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       *   Requested address
 72       * @param content
 73       *   The requested parameter format is: name = XXX & PWD = XXX
 74       * @param encoding
 75       *   Server side request encoding. Such as GBK,UTF-8, etc
 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(); // New connection instance
 84               connection.setConnectTimeout(2000);                     // Set connection timeout in milliseconds
 85               connection.setReadTimeout(2000);                        // Set read data timeout in milliseconds
 86               connection.setDoOutput(true);                           // Open output stream or not true|false
 87               connection.setDoInput(true);                            // Open input stream or not true|false
 88               connection.setRequestMethod("POST");                    // Submission method POST|GET
 89               connection.setUseCaches(false);                         // Cache or not true|false
 90               connection.connect();                                   // Open connection port
 91               DataOutputStream out = new DataOutputStream(connection.getOutputStream());// Open the output stream to write data to the opposite server
 92               out.writeBytes(content);                                // Write data,Submit your form name=xxx&pwd=xxx
 93               out.flush();                                            // Refresh
 94               out.close();                                            // Close output stream
 95               BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// Write data to the peer and return data to the peer server ,with BufferedReader Stream to read
 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();                            // Close connection
108               }
109           }
110           return null;
111       }
112 
113       /**
114        * unicode Convert to Chinese
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        }

The output is

IP====={"code":0,
    "data":{
      "ip":"221.232.245.73",   //ip
"country": "China", / / country
"Area": "", / / area
"region": "Hubei", / / Province
"city": "Wuhan", / / city
      "county":"XX",      
"isp": "Telecom", / / broadband operation
"Country" Id ":" CN ", / / country id
"Area" Id ":" ", / / area code
"Region" Id ":" 420000 ", / / Province code
"City" Id ":" 420100 ", / / city code
      "county_id":"xx",     
      "isp_id":"100017"}} region = Wuhan Length of temp = 14 China = = Wuhan = Telecom = = 420100

Posted by aaadispatch on Tue, 05 May 2020 04:19:22 -0700