根据ip获取对应的城市

需要用jar包和工具,下载地址https://download.csdn.net/download/a229397620/12094631

把工具和jar包放好后,就可以理由下面的类进行测试

FileDispatcher工具类可以去查看博文https://blog.csdn.net/a229397620/article/details/108517663

import java.io.File;
import java.lang.reflect.Method;
 


import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

 
public class IPUtil{ 
    public static String getCityInfo(String ip){
 
    	//获取工具类地址,就是下载上面工具后,data的存放路径
        String filePath = FileDispatcher.getSavePath();
		String dbPath = filePath + "data/ip2region.db";
		
        File file = new File(dbPath);
        if ( file.exists() == false ) {
            System.out.println("Error: Invalid ip2region.db file");
        }
 
        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM;
        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);
            System.out.println(dataBlock.getCityId());
            return dataBlock.getRegion();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return null;
    }

}
String address = IPUtil.getCityInfo("220.248.12.158");
System.out.println("address=="+address);
if(address != null && address.trim().length() > 0){
    String[] addressArr = address.split("\\|");
	if(addressArr != null && addressArr.length >= 2){
		//logger.error("address2:"+);
		addressInfo = addressArr[addressArr.length - 2];
		if(addressInfo.trim().equals("0")){
			addressInfo = addressArr[2];
		}
		if(addressInfo.trim().equals("0")){
		    addressInfo = addressArr[0];
		}
	}
}

上面的ip地址输出是:中国|0|上海|上海市|联通,最终获得的省市是上海市,

因为国外的获取到的地址会有些不同,为了避免获取值是0,就做了判断,最少也会获取是国家

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值