Java通过IP获取位置信息

Java通过IP获取位置信息

离线库

    不使用Api获取地址

使用方式:

    导入依赖
<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>2.6.4</version>
</dependency>
//把ip2region.xdb文件丢到resources路径下
String dbPath = "/ip2region/ip2region.xdb";
String path = Test.class.getResource(dbPath).getPath();
byte[] cBuff = Searcher.loadContentFromFile(path);
Searcher searcher = Searcher.newWithBuffer(cBuff);
String search = searcher.search("127.0.0.1");
String province = search.split("\|")[2];
System.out.println("province = " + province);
System.out.println("search = " + search);

//控制台打印
province = 上海
search = 中国|0|上海|上海市|电信

踩过的坑

java.io.FileNotFoundExeption: …/app.jar!/BOOT-INF/classess!/ip2region/ip2region.xdb(No such file or directory) 容器部署的项目,打的是jar包,这个路径是不存在于磁盘上的,所以部署后读取不到该路径!!!!

解决方案:

//把ip2region.xdb文件丢到resources路径下
String dbPath = "/ip2region/ip2region.xdb";
//获取流
InputStream inputStream = Test.class.getResourceAsStream(dbPath);
File file = new File("your path");
//流写入文件
FileUtils.copyInputStreamToFile(inputStream,file);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
byte[] cBuff = Searcher.loadContent(randomAccessFile);
Searcher searcher = Searcher.newWithBuffer(cBuff);
String search = searcher.search("127.0.0.1");
System.out.println("search = " + search);

//控制台打印
search = 中国|0|上海|上海市|电信

第三方地图软件Api

    高德 百度地图 腾讯地图 等等

通过各大地图平台提供的Api接口

    特性: 需要提前注册账号(公司项目账号捆绑于个人?) Api有停用风险 可能收费(自己去调研?) 公司内网不能直接访问(开墙解决) 等等

高德地图:

    服务请求示例:https://restapi.amap.com/v3/ip?ip=114.247.50.2&output=xml&key=<用户的key> 图片示例:

百度地图:

    服务请求示例:https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll 图片示例:

腾讯地图:

第一篇博客,感谢支持!!!

经验分享 程序员 微信小程序 职场和发展