Java 根据 IP 获取地理位置

栏目: Java · 发布时间: 6年前

内容简介:GeoLite2 提供了两种方式根据 IP 获取地理位置::point_down:以本地数据库方式演示,请注意数据库 License:编辑 pom.xml 文件,添加依赖:

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

  • 本地数据库
  • Web Service

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

依赖

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

<dependency>  
    <groupId>com.maxmind.geoip2</groupId>
    <artifactId>geoip2</artifactId>
    <version>2.12.0</version>
</dependency>

下载数据库

本地数据库 下载地址 ,解压缩到工程的 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)和英文城市名称。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Applications (Hacking Exposed)

Web Applications (Hacking Exposed)

Joel Scambray、Mike Shema / McGraw-Hill Osborne Media / 2002-06-19 / USD 49.99

Get in-depth coverage of Web application platforms and their vulnerabilities, presented the same popular format as the international bestseller, Hacking Exposed. Covering hacking scenarios across diff......一起来看看 《Web Applications (Hacking Exposed)》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码