A few days ago, I wanted to add a function to analyze the geographical location of the IP address in the backend of the website. I read some blogs on the Internet and found a few programs, but I always felt that the writing was not concise enough and felt verbose. The program below seems quite simple, so I sorted it out and debugged it. It can be used. The program calls the interface provided by "Tencent IP Sharing Plan". Of course, it can also be changed to the interface provided by ip138. However, the strings returned by these two websites The formats are somewhat different and must be parsed separately.
public String getAddressByIP(){ try { String strIP = "0.0.0.0"; URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK")); String line = null; StringBuffer result = new StringBuffer(); while((line = reader.readLine()) != null) { result.append(line); } reader.close(); strIP = result.substring(result.indexOf( "The location of this IP is:" )); strIP = strIP.substring(strIP.indexOf( ":") + 1); String province = strIP.substring(6, strIP.indexOf("province")); String city = strIP.substring(strIP.indexOf("province") + 1, strIP.indexOf("city")); ... ... ... ... } catch(IOException e) { return "Read failed"; }}
Attached:
Sina interface: http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=
Taobao interface: http://ip.taobao.com/service/getIpInfo.php?ip=[ip address string]