离线版本:
依赖:
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;
}
}