栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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


前言

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


一、GeoLite2-City.mmdb是什么?

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

二、使用步骤 1.引入库

代码如下(示例):

        
        
            com.maxmind.geoip2
            geoip2
            2.8.1
        
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

    }


总结

运行截图展示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/825561.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号