1. 方式一:
如果你可以拿到你的外网IP。
可以使用淘宝接口"http://ip.taobao.com/service/getIpInfo.php?ip=",地址后面跟上你的IP即可查询出来。相似的接口还有新浪和腾讯的,可以网上搜到。
上面接口返回数据:
{
"code":0,
"data":{
"ip":"你的IP","country":"中国","area":"","region":"省份",
"city":"城 市","county":"XX","isp":"运营商",
"country_id":"CN","area_id":"","region_id":"省份ID","city_id":"城市ID",
"county_id":"xx","isp_id":"运营商编号"}
}
获取本机或其他IP地址的归属地也可以使用接口"http://whois.pconline.com.cn/ipJson.jsp?ip={你要查询的IP地址}&json=true",返回格式:
{"ip":"58.112.208.119","pro":"","proCode":"999999","city":"","cityCode":"0","region":"","regionCode":"0","addr":" 日本","regionNames":"","err":"noprovince"}
2. 方式二:
如果你想直接查询本机的IP和归属地。
实现思路
现在都有查询归属地的网站,我们访问那个网站,会返回一个页面,上面会有IP信息和归属地,然后再截取一下关键数据即可得到想要的东西了;
实现例子
以"http://www.ip138.com/"为例,相似的网站还有"https://ip.cn/"等网站,但是截取方式不通用。
public static void main( String[] args ) {
HttpRequest request = HttpUtil.createGet("http://2019.ip138.com/ic.asp");
HttpResponse response = request.execute();
String str = response.body();
String regex = "<center>(.*?)</center>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
}
上面代码打印出来
您的IP是:[11.22.33.44] 来自:湖南省长沙市 电信