1、添加依赖
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7</version>
</dependency>
2、工具类
public class IPUtil {
public static String getCityInfo(String ip){
//db
String dbPath = IPUtil.class.getResource("/ip2region.db").getPath();
File file = new File(dbPath);
if ( file.exists() == false ) {
System.out.println("Error: Invalid ip2region.db file");
}
//查询算法
int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
//DbSearcher.BINARY_ALGORITHM //Binary
//DbSearcher.MEMORY_ALGORITYM //Memory
try {
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, dbPath);
//define the method
Method method = null;
switch ( algorithm )
{
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
DataBlock dataBlock = null;
if (Util.isIpAddress(ip) == false ) {
System.out.println("Error: Invalid ip address");
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3、下载文件ip2region.db到resources文件夹下
$ git clone https://gitee.com/lionsoul/ip2region.git
下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下
本文详细介绍了一种基于ip2region库的IP地址定位方法,通过在Java项目中添加依赖并使用特定工具类,实现了从IP地址获取地理位置信息的功能。文章提供了具体代码示例,包括依赖配置、工具类定义及数据库文件的正确使用。
440

被折叠的 条评论
为什么被折叠?



