如何根据IP地址获取地理位置?

时间:2021-07-21 10:41:58
/**
* 根据IP地址获取地理位置
*/
public String getAddressByIP(String ip) {
try {
URL url = new URL("http://www.ip138.com/ips138.asp?ip=" + ip);
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();
char[] address=null;
address = result.substring(result.indexOf("主数据:") + 4,
result.indexOf("</li><li>参考数据"));
address = ip.toCharArray();
System.out.println(address);//输出地址
} catch (Exception e) {
e.printStackTrace();
}
return address;
}