Java implements code sharing to get geographical locations based on IP addresses

  • 2020-04-01 03:26:50
  • OfStack

A few days ago, I want to add a function of analyzing the location of IP in the background of the website. I read some blogs on the Internet and found a few procedures, but I always feel that what I wrote is not concise enough, which makes me feel wordy. The following program, the feeling is still relatively concise, so the arrangement debugging, can be used, the program called the "tencent IP sharing plan" interface, of course, can be changed to the interface provided by ip138, but the two sites returned some different string format, to do the analysis respectively.


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 IP Location: " ));
    strIP = strIP.substring(strIP.indexOf( " : ") + 1);
    String province = strIP.substring(6, strIP.indexOf(" province "));
    String city = strIP.substring(strIP.indexOf(" province ") + 1, strIP.indexOf(" The city "));
    ... ...
    ... ...
  }
  catch( IOException e)
  { 
    return " Read failure "; 
  }
}

The 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]


Related articles: