springboot GeoLite2-City.mmdb实现通过IP地址获取经纬度以及该IP的所属地区

springboot GeoLite2-City.mmdb实现通过IP地址获取经纬度以及该IP的所属地区,第1张

文章目录
  • 前言
  • 一、GeoLite2-City.mmdb是什么?
  • 二、使用步骤
    • 1.引入库
    • 2.将GeoLite2-City.mmdb文件拷贝到项目根目录
    • 3.编写main方法测试
  • 总结


前言

通过输入一个IP地址,解析并获取信息,比如国家、国家代码、省份、省份代码、城市、邮政编码、经纬度等等信息


一、GeoLite2-City.mmdb是什么?

官网地址:官方网站
GeoLite2 数据库是免费的 IP 地理定位数据库

二、使用步骤 1.引入库

代码如下(示例):

        
        <dependency>
            <groupId>com.maxmind.geoip2groupId>
            <artifactId>geoip2artifactId>
            <version>2.8.1version>
        dependency>
2.将GeoLite2-City.mmdb文件拷贝到项目根目录

GeoLite2-City.mmdb下载地址:下载地址

3.编写main方法测试

代码如下(示例):

    public static void main(String[] args) throws Exception {
        // 创建 GeoLite2 数据库

        String destFilePath = new File("GeoLite2-City.mmdb").getAbsolutePath();
        File database = new File(destFilePath);

        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        InetAddress ipAddress = InetAddress.getByName("xxxxxxxxxxxxx");//要解析的ip地址

        // 获取查询结果
        CityResponse 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());   // 'Guangxi'
        System.out.println(subdivision.getIsoCode()); // 'GX'
        System.out.println(subdivision.getNames().get("zh-CN")); // '广西壮族自治区'

        // 获取城市
        City city = response.getCity();
        System.out.println(city.getName()); // 'Guilin'
        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());  // 25.2802
        System.out.println(location.getLongitude()); // 110.2964

    }


总结

运行截图展示:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/719909.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存