ipregistry/ipregistry-java
GitHub: ipregistry/ipregistry-java
Ipregistry 官方 Java 客户端库,为 Java 应用提供高性能的 IP 地理定位与威胁数据查询能力,内置缓存、重试、异步支持和批量查询功能。
Stars: 16 | Forks: 4
[
](https://ipregistry.co/)
# Ipregistry Java 客户端库
[](LICENSE)
[](https://github.com/ipregistry/ipregistry-java/actions)
[](https://search.maven.org/search?q=g:co.ipregistry%20AND%20a:ipregistry-client)
[](https://www.javadoc.io/doc/co.ipregistry/ipregistry-client)
这是 [Ipregistry](https://ipregistry.co) IP 地理定位和威胁数据 API 的官方 Java 客户端库,
允许您查找自己的 IP 地址或指定的 IP 地址。响应会返回多个数据点,包括
运营商、公司、货币、位置、时区、威胁信息等。
## 快速入门
您需要一个 Ipregistry API key,您可以通过在 [https://ipregistry.co](https://ipregistry.co) 注册免费帐户来获取,并获得 100,000 次免费查找。
### 安装
#### Maven
```
co.ipregistry
ipregistry-client
6.1.0
```
#### Gradle
```
implementation 'co.ipregistry:ipregistry-client:6.1.0'
```
### 快速开始
#### 单个 IP 查找
```
import co.ipregistry.api.client.exceptions.ApiException;
import co.ipregistry.api.client.exceptions.ClientException;
import co.ipregistry.api.client.model.IpInfo;
public class SingleIpLookup {
public static void main(final String[] args) {
final IpregistryClient client = new IpregistryClient("YOUR_API_KEY");
try {
// Here is an example to lookup IP address data for a given IP address.
// The parameter to pass is an IPv4 or IPv6 address.
// On server-side, you need to retrieve the client IP from the request headers.
final IpInfo ipInfo = client.lookup("54.85.132.205");
System.out.println(ipInfo);
// If your purpose is to perform a lookup for the current node and network interface
// used to execute this code, then you don't even need to pass a parameter
final RequesterIpInfo requesterIpInfo = client.lookup();
System.out.println(requesterIpInfo);
} catch (final ApiException e) {
// Handle API errors (e.g. insufficient credits, throttling) here
e.printStackTrace();
} catch (final ClientException e) {
// Handle client errors (e.g. network error) here
e.printStackTrace();
}
}
}
```
#### 批量 IP 查找
```
import co.ipregistry.api.client.ipregistrygistry;
import co.ipregistry.api.client.exceptions.ApiException;
import co.ipregistry.api.client.exceptions.ClientException;
import co.ipregistry.api.client.exceptions.IpInfoException;
import co.ipregistry.api.client.model.IpInfo;
import co.ipregistry.api.client.model.IpInfoList;
import java.util.Arrays;
public class BatchIpLookup {
public static void main(final String[] args) {
final IpregistryClient client = new IpregistryClient("YOUR_API_KEY");
try {
final IpInfoList ipInfoList =
client.lookup(Arrays.asList("73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"));
for (int i = 0; i < ipInfoList.size(); i++) {
try {
final IpInfo ipInfo = ipInfoList.get(i);
// Here is an example to print out the country name associated with each IP address
System.out.println(ipInfo.getLocation().getCountry().getName());
} catch (final IpInfoException e) {
// Handle batch lookup error (e.g. invalid IP address) here
e.printStackTrace();
}
}
} catch (final ApiException e) {
// Handle API errors (e.g. insufficient credits, throttling) here
e.printStackTrace();
} catch (final ClientException e) {
// Handle client errors (e.g. network error) here
e.printStackTrace();
}
}
}
```
## 缓存
虽然 Ipregistry 客户端库内置了对内存缓存的支持,但为了确保数据的新鲜度,默认情况下它是禁用的。
要启用内存缓存,请将 _InMemoryCache_ 的实例传递给 Ipregistry 客户端:
```
IpregistryConfig config =
IpregistryConfig.builder()
.apiKey("YOUR_API_KEY").build();
IpregistryClient ipregistry = new IpregistryClient(config, InMemoryCache.builder().build());
```
_InMemoryCache_ 实现支持多种淘汰策略(例如基于大小、基于时间):
```
InMemoryCache cache =
InMemoryCache.builder()
.concurrencyLevel(16)
.expireAfter(600 * 1000)
.initialCapacity(512)
.maximumSize(4096)
.build();
```
您也可以通过实现 _IpregistryCache_ 接口来提供自己的缓存实现。
## 重试
失败的请求会通过指数退避自动重试。默认情况下,对于暂时性的网络错误和 5xx 服务器响应,最多会执行 3 次重试。
由于 Ipregistry 默认不进行速率限制(速率限制是针对每个 API key 可选开启的),因此针对 _429 Too Many Requests_ 响应的重试**默认是禁用的**。如果您的 API key 配置了速率限制,并且您希望客户端等待并重试(在存在时遵循 `Retry-After` header),请启用它:
```
IpregistryConfig config =
IpregistryConfig.builder()
.apiKey("YOUR_API_KEY")
.retryMaxAttempts(3) // 0 disables retries entirely
.retryInterval(1000) // base backoff in milliseconds
.retryOnServerError(true) // retry on 5xx (default: true)
.retryOnTooManyRequests(true) // retry on 429 (default: false)
.build();
```
## 自定义 HTTP 客户端
默认情况下,客户端管理着自己的 Apache HttpClient 5 实例(连接池、超时、重试)。要获得完全控制权——包括连接池大小、代理、自定义 TLS 或指标——请提供您自己的 `CloseableHttpClient`:
```
CloseableHttpClient httpClient = HttpClients.custom()
// ... your connection manager, proxy, TLS, retry strategy, etc.
.build();
IpregistryConfig config =
IpregistryConfig.builder().apiKey("YOUR_API_KEY").build();
IpregistryClient ipregistry =
new IpregistryClient(config, NoCache.getInstance(), httpClient);
```
当您提供自己的客户端时,您将拥有其生命周期:当 Ipregistry 客户端关闭时,它**不会**被关闭,并且 `IpregistryConfig` 中的超时/重试设置将被忽略,转而使用您客户端自己的配置。
## 异步 API
每个查找和解析方法都有一个返回 `CompletableFuture` 的异步变体,适合用于组合非阻塞 pipeline:
```
IpregistryClient ipregistry = new IpregistryClient("YOUR_API_KEY");
ipregistry.lookupAsync("8.8.8.8")
.thenAccept(info -> System.out.println(info.getLocation().getCountry().getName()))
.exceptionally(error -> {
error.getCause().printStackTrace(); // ApiException or ClientException
return null;
});
```
这些 future 由每个任务一个虚拟线程的 executor(Java 21+)提供支持,因此数千个并发查找的成本非常低。失败的请求会以同步 API 抛出的相同 `ApiException`/`ClientException` 异常完成 future(包装在 `CompletionException` 中,因此需通过 `getCause()` 解包)。
要使用您自己的 executor,请在配置中进行设置。这样您就拥有了它的生命周期:当客户端关闭时,它不会被关闭。
```
IpregistryConfig config =
IpregistryConfig.builder()
.apiKey("YOUR_API_KEY")
.executor(myExecutorService)
.build();
```
响应式用户可以直接桥接这些 future,例如使用 `Mono.fromFuture(...)` (Reactor) 或 `Single.fromCompletionStage(...)` (RxJava)。
## 错误
所有 Ipregistry 异常都继承自 _IpregistryException_ 类。
主要子类是 _ApiException_ 和 _ClientException_。
_ApiException_ 类型的异常包含一个 code 字段,该字段映射到 [Ipregistry 文档](https://ipregistry.co/docs/errors) 中描述的 code。
除了原始字符串 `code` 外,_ApiException_ 还通过 `getErrorCode()` 暴露了一个类型化的 `ErrorCode`,因此您可以根据错误条件进行分支处理,而无需进行字符串匹配:
```
try {
IpInfo info = ipregistry.lookup("8.8.8.8");
} catch (ApiException e) {
ErrorCode code = e.getErrorCode(); // null if the raw code is not recognized
if (code == ErrorCode.INSUFFICIENT_CREDITS) {
// handle exhausted credits
} else if (code == ErrorCode.TOO_MANY_REQUESTS) {
// handle rate limiting
}
} catch (ClientException e) {
// handle client-side/network error
}
```
## 过滤机器人
您可能希望阻止爬虫或浏览您页面的机器人调用 Ipregistry API。
一种处理方法是通过 user agent 识别机器人。为了简化此过程,
该库包含了一个实用方法:
```
import co.ipregistry.api.client.ipregistrygistry;
import co.ipregistry.api.client.exceptions.ApiException;
import co.ipregistry.api.client.exceptions.ClientException;
import co.ipregistry.api.client.model.IpInfo;
import co.ipregistry.api.client.util.UserAgent;
public class SingleIpLookupFilteringBots {
public static void main(final String[] args) {
final IpregistryClient client = new IpregistryClient("YOUR_API_KEY");
// For testing purposes, you can retrieve you current user-agent value from:
// https://api.ipregistry.co/user_agent?key=YOUR_API_KEY (look at the field named "user_agent")
if (UserAgent.isBot("TO_REPLACE_BY_USER_AGENT_RETRIEVED_FROM_REQUEST_HEADER")) {
try {
final IpData ipInfo = client.lookup("8.8.8.8");
// Here is an example to print out the country name associated with the IP address
System.out.println(ipInfo.getLocation().getCountry().getName());
} catch (final ApiException e) {
// Handle API errors (e.g. insufficient credits, throttling) here
e.printStackTrace();
} catch (final ClientException e) {
// Handle client errors (e.g. network error) here
e.printStackTrace();
}
}
}
}
```
# 其他库
有适用于多种语言的官方 Ipregistry 客户端库,包括
[Javascript](https://github.com/ipregistry/ipregistry-javascript)、
[Python](https://github.com/ipregistry/ipregistry-python)、
[Typescript](https://github.com/ipregistry/ipregistry-javascript) 等等。
您是否正在寻找我们尚不支持的编程语言或框架的官方客户端?
[请告诉我们](mailto:support@ipregistry.co)。
标签:API客户端, IP地理定位, JS文件枚举, 后台面板检测, 域名枚举, 威胁情报, 开发者工具, 网络数据查询