一、简介
1.1 介绍
Determine the country, subdivisions (regions), city, and postal code associated with IPv4 and IPv6 addresses worldwide.
1.2 参考文档
https://dev.maxmind.com/geoip/docs/databases/city-and-country?lang=en#binary-databases
https://github.com/jianhuasun/GeoIP2-java
二、下载依赖库
2.1 下载地址:
tips: 需要注册登录
https://dev.maxmind.com/geoip/geolite2-free-geolocation-data?lang=en
打开页面登录点击: "Download Files"
三、项目中引依赖jar
Maven
We recommend installing this package with Maven. To do this, add the dependency to your pom.xml:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>3.0.1</version>
</dependency>
Gradle
Add the following to your build.gradle file:
repositories {
mavenCentral()
}
dependencies {
compile 'com.maxmind.geoip2:geoip2:3.0.1'
}
四、引入库并编写代码测试
// A File object pointing to your GeoIP2 or GeoLite2 database
File database = new File("/path/to/GeoIP2-City.mmdb");
// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'US'
System.out.println(country.getName()); // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'
City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 44.9733
System.out.println(location.getLongitude()); // -93.2323
五、常见问题
5.1 版本问题
jar 包版本3.0.1需要java11以上,2.16.1使用java8测试通过
5.2 按需引入
库分为城市和国家,GeoLite2-Country.mmdb 和 GeoLite2-City.mmdb
City库 包含了城市,文件较大(~64M),Country只有国家文件较小(~2M)。
版权属于:sunjianhua
本文链接:https://sunjianhua.cn/archives/java-ip-country-city.html
转载时须注明出处及本声明,如果不小心侵犯了您的权益,请联系邮箱:NTA2MTkzNjQ1QHFxLmNvbQ==