java地理位置的获取_Java 根据 IP 获取地理位置

GeoLite2 提供了两种方式根据 IP 获取地理位置:

本地数据库

Web Service

:point_down:以本地 数据库 方式演示,请注意数据库 License: CC BY-SA 4.0

依赖

编辑 pom.xml 文件,添加依赖:

com.maxmind.geoip2

geoip2

2.12.0

下载数据库

本地数据库 下载地址

,解压缩到工程的 Resources 目录。

代码

try (InputStream in = getClass().getClassLoader().getResourceAsStream("GeoLite2-City/GeoLite2-City.mmdb")) {

DatabaseReader reader = new DatabaseReader

.Builder(in)

.withCache(new CHMCache())

.build(); // ①

InetAddress ip = InetAddress.getByName("8.8.8.8");

CityResponse city = this.geoIPReader.city(ip); // ②

city.getCity().getNames().get("zh-CN"); // ③

city.getCity().getNames().get("en");

}

① 读取本地数据库;

② 根据 IP 地址获取城市信息;

③ 获取简体中文(zh-CN)和英文城市名称。

GeoLite2 提供了两种方式根据 IP 获取地理位置: 本地数据库 Web Service :point_down:以本地 数据库 方式演示,请注意数据库 License: CC BY-SA 4.0 。 依赖 编辑 pom.xml 文件,添加依赖: com.maxmind.geoip2 geoip2 2.12.0 下载数据库 本地数据库 下载地址 ,解压缩到工程的 Resources 目录。 代码 try (InputStream in = getClass().getClassLoader().getResourceAsStream("GeoLite2-City/GeoLite2-City.mmdb")) { DatabaseReader reader = new DatabaseReader .Builder(in) .withCache(new CHMCache()) .build(); // ① InetAddress ip = InetAddress.getByName("8.8.8.8"); CityResponse city = this.geoIPReader.city(ip); // ② city.getCity().getNames().get("zh-CN"); // ③ city.getCity().getNames().get("en"); } ① 读取本地数据库; ② 根据 IP 地址获取城市信息; ③ 获取简体中文(zh-CN)和英文城市名称。
经验分享 程序员 微信小程序 职场和发展