通过IP地址获取相应的城市
使用GeoLite2 City库
GeoLite2 City下载地址:http://dev.maxmind.com/geoip/geoip2/geolite2/
下载完后解压,保存目录路径
在maven项目中的pom.xml配置文件添加依赖
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.1</version>
</dependency>
通过GeoLite2查询得到省份、城市
public static void main(String[] args) throws IOException {
// 创建 GeoLite2 数据库
File database = new File("C:/Users/12059/Desktop/GeoLite2-City_20190326/GeoLite2-City.mmdb");
// 读取数据库内容
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("219.136.134.157");
// 获取查询结果
CityResponse response = null;
try {
response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'CN'
System.out.println(country.getName()); // 'China'
System.out.println(country.getNames().get("zh-CN")); // '中国'
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Guangdong'
System.out.println(subdivision.getIsoCode()); // 'GD'
System.out.println(subdivision.getNames().get("zh-CN")); // '广东'
// 获取城市
City city = response.getCity();
System.out.println(city.getName()); // 'Guangzhou'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // 'null'
System.out.println(city.getNames().get("zh-CN")); // '广州'
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 23.1167
System.out.println(location.getLongitude()); // 113.25
} catch (GeoIp2Exception e) {
e.printStackTrace();
}
}
此处注意,该路径换成存放GeoLite2-City.mmdb的路径
File database = new File("C:/Users/12059/Desktop/GeoLite2-City_20190326/GeoLite2-City.mmdb");
运行结果: