利用com.maxmind.db根据ip地址获取地理位置信息

利用com.maxmind.db根据ip地址获取地理位置信息

1 添加Maven依赖

<dependency>
    <groupId>com.maxmind.db</groupId>
    <artifactId>maxmind-db</artifactId>
    <version>1.0.0</version>
</dependency>

2 用法

2.1 简单示例

File database = new File("/path/to/database/GeoIP2-City.mmdb");
Reader reader = new Reader(database);

InetAddress address = InetAddress.getByName("24.24.24.24");

JsonNode response = reader.get(address);

System.out.println(response);

reader.close();

案例(获取国家和省份信息工具类)

import com.fasterxml.jackson.databind.JsonNode;
import com.maxmind.db.Reader;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

public class GeoLiteUtil {
    private static Reader reader = null;

    private static Map<String, String> cache = new HashMap<String, String>();

    static {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream in = loader.getResource("GeoLite2-City.mmdb").openStream();
            reader = new Reader(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取条目
     *
     * @param ip
     * @return
     */
    public static String getEntry(String ip) {
        String entry = cache.get(ip);
        try {
            if (entry == null) {
                JsonNode node = reader.get(InetAddress.getByName(ip));
                if (node == null){
                    return "未知国家,未知省份";
                }
                String country = node.get("country").get("names").get("zh-CN").textValue();
                String province = node.get("subdivisions").get(0).get("names").get("zh-CN").textValue();
                entry = country + "," + province;
                cache.put(ip, entry);
            }

        } catch (IOException e) {
            System.out.println(ip + " = null");
        }
        return entry;
    }

    public static String getCountry(String ip) {
        String entry = getEntry(ip);
        if (entry != null) {
            return entry.split(",")[0];
        }
        return null;
    }

    public static String getProvince(String ip) {
        String entry = getEntry(ip);
        if (entry != null) {
            return entry.split(",")[1];
        }
        return null;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值