java 根据IP获取城市与经纬度(第一种)

    技术2022-07-14  64

    最近需要做一个拨打电话的功能, 调用第三方接口进行拨号, 而接口中要求经纬度为必传字段, 虽然可以通过app或小程序端获取, 但还是想看看能否通过java来获取到这些具体数据值, 以下为本人查找资料与文档总结出第一种实现方案! 此方法需要用到 GeoIP - > 下载地址

    注意: 1. 下载使用 GeoIP需要简单的注册一下 2. GeoIP官网上有很多具有倾向性的完整数据, 但有部分是收费的! 3. 此处摘取GeoIP官网中部分需要注意的内容

    *GeoLite2免费可下载数据库* 由于即将颁布的数据隐私法规,我们将从2019年12月30日开始对您访问免费的GeoLite2数据库的方式进行重大更改。在我们的博客上了解更多信息。 *资料库* GeoLite2数据库是免费的IP地理位置数据库,可与MaxMind的GeoIP2数据库相比,但准确性较差。GeoLite2国家/地区,城市和ASN数据库每周两次更新。 *IP地理位置使用* IP地理位置固有地不精确。位置通常靠近人口中心。GeoIP数据库提供的任何位置都不应用于标识特定地址或家庭。 使用Accuracy Radius作为我们为IP地址返回的纬度和经度坐标的地理位置精度的指示。IP地址的实际位置可能在此半径以及经纬度坐标定义的区域内。

    下载内容

    下载下来的文件包中GeoLite2-City.mmdb文件就是我们所需要的!将此文件放入项目中 接下来就可以开始谢谢项目代码了 首先我们需要在pom.xml文件中添加引用(maven项目)

    <!-- 根据ip获取位置 --> <dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version>2.14.0</version> </dependency>

    现在可以编写我们的工具类了, 相关代码如下

    package com.example.demo.utils; import com.fasterxml.jackson.databind.JsonNode; import com.maxmind.db.Reader; import com.maxmind.db.Record; import com.maxmind.geoip2.DatabaseReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; /** * * @description: 获取客户端IP地址/根据IP地址获取所在区域及经纬度 * @author: lcx * @since: 2020年07月02日 上午11:25:51 */ public class IPUtils { private static Logger logger = LoggerFactory.getLogger(IPUtils.class); private final static String INTRANET_LOCAL_IP = "127.0.0.1"; /** * 获取客户端真实IP * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址, * X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 */ public static String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if (ip.equals(INTRANET_LOCAL_IP)) { // 根据网卡取本机配置的IP InetAddress inet; try { inet = InetAddress.getLocalHost(); if (null != inet) { ip = inet.getHostAddress(); } } catch (UnknownHostException e) { e.printStackTrace(); } } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ip != null && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } /** * * @description: 获得国家 * @param reader * @param ip * @return * @throws Exception */ public static String getCountry(DatabaseReader reader, String ip) throws Exception { return reader.city(InetAddress.getByName(ip)).getCountry().getNames().get("zh-CN"); } /** * * @description: 获得省份 * @param reader * @param ip * @return * @throws Exception */ public static String getProvince(DatabaseReader reader, String ip) throws Exception { return reader.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN"); } /** * * @description: 获得城市 * @param reader * @param ip * @return * @throws Exception */ public static String getCity(DatabaseReader reader, String ip) throws Exception { return reader.city(InetAddress.getByName(ip)).getCity().getNames().get("zh-CN"); } /** * * @description: 获得经度 * @param reader * @param ip * @return * @throws Exception */ public static Double getLongitude(DatabaseReader reader, String ip) throws Exception { return reader.city(InetAddress.getByName(ip)).getLocation().getLongitude(); } /** * * @description: 获得纬度 * @param reader * @param ip * @return * @throws Exception */ public static Double getLatitude(DatabaseReader reader, String ip) throws Exception { return reader.city(InetAddress.getByName(ip)).getLocation().getLatitude(); } public static void main(String[] args) throws Exception { String ip = "115.236.64.138"; // 访问IP // 实际项目中可存放在resources下通过注解加载或配置pom.xml文件启动项目时加载扫描均可,若有更简便方式更好 String path = "E:/workspace/demo/src/main/resources/db/GeoLite2-City.mmdb"; // 创建 GeoLite2 数据库 File database = new File(path); test1(ip, database); System.out.println(".............................................................."); test2(ip, database); } private static void test1(String ip, File database)throws Exception{ // 读取数据库内容 DatabaseReader reader = new DatabaseReader.Builder(database).build(); String address1 = IPUtils.getCountry(reader, ip) + "-" + IPUtils.getProvince(reader, ip) + "-" + IPUtils.getCity(reader, ip) + "-" + IPUtils.getLongitude(reader, ip)+ "-" + IPUtils.getLatitude(reader, ip); System.out.println(address1); } private static void test2(String ip, File database)throws Exception{ try (Reader reader = new Reader(database)) { InetAddress address = InetAddress.getByName(ip); // get() returns just the data for the associated record JsonNode recordData = reader.get(address); System.out.println(recordData); // getRecord() returns a Record class that contains both // the data for the record and associated metadata. Record record = reader.getRecord(address); System.out.println(record.getData()); System.out.println(record.getNetwork()); } } }

    可以看一下执行结果

    中国-浙江省-杭州-120.1619-30.294 .............................................................. {"continent":{"code":"AS","names":{"de":"Asien","ru":"Азия","pt-BR":"Ásia","ja":"アジア","en":"Asia","fr":"Asie","zh-CN":"亚洲","es":"Asia"},"geoname_id":6255147},"country":{"names":{"de":"China","ru":"Китай","pt-BR":"China","ja":"中国","en":"China","fr":"Chine","zh-CN":"中国","es":"China"},"iso_code":"CN","geoname_id":1814991},"city":{"geoname_id":1808926,"names":{"de":"Hangzhou","ru":"Ханчжоу","pt-BR":"Hangzhou","ja":"杭州市","en":"Hangzhou","fr":"Hangzhou","zh-CN":"杭州","es":"Hangzhou"}},"location":{"accuracy_radius":1,"time_zone":"Asia/Shanghai","latitude":30.294,"longitude":120.1619},"registered_country":{"names":{"de":"China","ru":"Китай","pt-BR":"China","ja":"中国","en":"China","fr":"Chine","zh-CN":"中国","es":"China"},"iso_code":"CN","geoname_id":1814991},"subdivisions":[{"names":{"en":"Zhejiang","fr":"Province de Zhejiang","zh-CN":"浙江省"},"iso_code":"ZJ","geoname_id":1784764}]} {"continent":{"code":"AS","names":{"de":"Asien","ru":"Азия","pt-BR":"Ásia","ja":"アジア","en":"Asia","fr":"Asie","zh-CN":"亚洲","es":"Asia"},"geoname_id":6255147},"country":{"names":{"de":"China","ru":"Китай","pt-BR":"China","ja":"中国","en":"China","fr":"Chine","zh-CN":"中国","es":"China"},"iso_code":"CN","geoname_id":1814991},"city":{"geoname_id":1808926,"names":{"de":"Hangzhou","ru":"Ханчжоу","pt-BR":"Hangzhou","ja":"杭州市","en":"Hangzhou","fr":"Hangzhou","zh-CN":"杭州","es":"Hangzhou"}},"location":{"accuracy_radius":1,"time_zone":"Asia/Shanghai","latitude":30.294,"longitude":120.1619},"registered_country":{"names":{"de":"China","ru":"Китай","pt-BR":"China","ja":"中国","en":"China","fr":"Chine","zh-CN":"中国","es":"China"},"iso_code":"CN","geoname_id":1814991},"subdivisions":[{"names":{"en":"Zhejiang","fr":"Province de Zhejiang","zh-CN":"浙江省"},"iso_code":"ZJ","geoname_id":1784764}]} 115.236.64.0/21

    第一种方式直接调用方法获取具体的数据, 第二种方法是获取的db表中的符合条件的全部数据, 可以根据自己的需要进行后续代码调整编写

    GeoIP 官网上 同时提供了MaxMind支持的API链接地址 感兴趣的可以将项目下载下来看看哦!

    Processed: 0.013, SQL: 9