java 根据ip获取地区信息

离线版本:

依赖:

maven

<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>1.7</version>
</dependency>

gradle

    implementation 'org.lionsoul:ip2region:2.7.0'

dome:

注:ip2region.xdb 离线版本库  

链接:https://pan.baidu.com/s/1yEQXrEsfi-RFOAd1fK1bdw?pwd=n6nn 

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import java.io.InputStream;


public static void main(String[] args) throws Exception {
        // 1、创建 searcher 对象
        String dbPath = "/ip2region/ip2region.xdb";
        Searcher searcher = null;
        try {
            InputStream inputStream = new ClassPathResource(dbPath).getInputStream();
            byte[] dbBinStr = FileCopyUtils.copyToByteArray(inputStream);
            // 创建一个完全基于内存的查询对象
            searcher = Searcher.newWithBuffer(dbBinStr);
        } catch (Exception e) {
            System.out.printf("failed to create content cached searcher: %s\n", e);
        }
        //把ip2r
        String address = "";
        try {
            address = searcher.search("66.249.79.193");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("=== 访问者的地址为:"+address+" === ");

        // 3、关闭资源
        searcher.close();

        // 备注:并发使用,每个线程需要创建一个独立的 searcher 对象单独使用。
    }

结果:

 

在线版本:

public static String getAddress(String ip) {
    try {
        URL realUrl = new URL("http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true");
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setReadTimeout(6000);
        conn.setConnectTimeout(6000);
        conn.setInstanceFollowRedirects(false);
        int code = conn.getResponseCode();
        StringBuilder sb = new StringBuilder();
        String ipaddr = "";
        if (code == 200) {
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            ipaddr = ip + "=" + sb.substring(sb.indexOf("addr") + 7, sb.indexOf("regionNames") - 3);
        }
        return ipaddr;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值