unirest-java-3
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnirest-Java 3.x Reference (v3.14.5)
Unirest-Java 3.x 参考文档(v3.14.5)
This skill covers the Unirest-Java 3.x HTTP client library for Java 8+. It uses Apache HttpClient 4 as the HTTP engine and includes GSON as the default JSON parser.
本 skill 涵盖适用于 Java 8+ 的 Unirest-Java 3.x HTTP 客户端库。它使用 Apache HttpClient 4 作为 HTTP 引擎,并将 GSON 作为默认 JSON 解析器。
Capability Boundaries
能力边界
✅ Strong Suits
✅ 适用场景
- Building HTTP requests (GET, POST, PUT, DELETE, PATCH) with fluent API
- JSON/object mapping with built-in GSON (no extra dependency needed)
- Async requests with CompletableFuture (via Apache HttpAsyncClient)
- File uploads with progress monitoring
- Mock testing for HTTP clients
- Response caching with configurable eviction
- Proxy configuration (simple, system, per-request)
- Request/response interceptors for logging and auth
- Connection pool tuning ()
concurrency(total, perRoute) - Socket timeout control (independent of connect timeout)
- Automatic retries on socket errors ()
automaticRetries() - Shutdown hooks for background thread management
- Custom HostnameVerifier support
- 使用流畅 API 构建 HTTP 请求(GET、POST、PUT、DELETE、PATCH)
- 使用内置 GSON 进行 JSON/对象映射(无需额外依赖)
- 通过 CompletableFuture 发起异步请求(基于 Apache HttpAsyncClient)
- 文件上传及进度监控
- 针对 HTTP 客户端进行模拟测试
- 可配置驱逐策略的响应缓存
- 代理配置(简单代理、系统代理、单请求代理)
- 用于日志记录和身份验证的请求/响应拦截器
- 连接池调优()
concurrency(total, perRoute) - Socket 超时控制(独立于连接超时)
- Socket 错误自动重试()
automaticRetries() - 用于管理后台线程的关闭钩子
- 支持自定义 HostnameVerifier
⚠️ Requirements
⚠️ 要求
- Java 8 or higher
- Apache HttpClient 4 (transitive dependency)
- Maven/Gradle dependency management
- Java 8 或更高版本
- Apache HttpClient 4(传递依赖)
- Maven/Gradle 依赖管理
❌ Out of Scope (with alternatives)
❌ 不在范围内(替代方案)
- HTTP/2 → use Unirest 4.x (defaults to HTTP/2)
- WebSocket via Unirest → use Apache HttpClient WebSocket or dedicated library
- Server-Sent Events (SSE) → use Unirest 4.x or custom implementation
- Custom executor support → not available in 3.x
- Java Authenticator integration → use Apache-specific auth mechanisms
- ProxySelector support → use per-request proxies or system properties
- HTTP/2 → 使用 Unirest 4.x(默认使用 HTTP/2)
- 通过 Unirest 使用 WebSocket → 使用 Apache HttpClient WebSocket 或专用库
- Server-Sent Events(SSE)→ 使用 Unirest 4.x 或自定义实现
- 自定义 executor 支持 → 3.x 不支持
- Java Authenticator 集成 → 使用 Apache 特有的身份验证机制
- ProxySelector 支持 → 使用单请求代理或系统属性
When to Use This Skill
何时使用本 skill
Use this skill when the user needs to:
- Make HTTP requests to REST APIs in Java 8+ projects
- Use Apache HttpClient as the HTTP engine
- Have built-in GSON without extra dependencies
- Tune connection pools ()
concurrency() - Control socket timeout independently
- Use automatic retries on socket errors
- Configure per-request proxies
- Use custom HostnameVerifier
当用户需要以下功能时,使用本 skill:
- 在 Java 8+ 项目中向 REST API 发起 HTTP 请求
- 使用 Apache HttpClient 作为 HTTP 引擎
- 无需额外依赖即可使用内置 GSON
- 调整连接池()
concurrency() - 独立控制 socket 超时
- 对 socket 错误启用自动重试
- 配置单请求代理
- 使用自定义 HostnameVerifier
Quick Start
快速开始
Maven dependency (Unirest 3.14.5):
xml
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.14.5</version>
</dependency>✅ No JSON module declaration needed — GSON is included by default.
Minimal GET request:
java
String body = Unirest.get("https://api.example.com/users")
.asString()
.getBody();Minimal POST with JSON:
java
HttpResponse<JsonNode> response = Unirest.post("https://api.example.com/users")
.header("Content-Type", "application/json")
.body(new User("Alice", "alice@example.com"))
.asJson();Maven 依赖(Unirest 3.14.5):
xml
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.14.5</version>
</dependency>✅ 无需声明 JSON 模块 — 默认已包含 GSON。
最小 GET 请求:
java
String body = Unirest.get("https://api.example.com/users")
.asString()
.getBody();使用 JSON 的最小 POST 请求:
java
HttpResponse<JsonNode> response = Unirest.post("https://api.example.com/users")
.header("Content-Type", "application/json")
.body(new User("Alice", "alice@example.com"))
.asJson();Critical: Installation
关键:安装
Unirest 3.x is a single dependency that includes GSON by default:
xml
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.14.5</version>
</dependency>✅ No need to declare a separate JSON module —(GSON-based) is included.JsonObjectMapper
Unirest 3.x 只需一个依赖,默认包含 GSON:
xml
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.14.5</version>
</dependency>✅ 无需单独声明 JSON 模块 — 已包含基于 GSON 的。JsonObjectMapper
Critical: Configuration
关键:配置
All configuration goes through :
Unirest.config()java
Unirest.config()
.connectTimeout(5000)
.socketTimeout(10000)
.concurrency(200, 20)
.setDefaultHeader("Accept", "application/json")
.setDefaultBasicAuth("user", "pass")
.followRedirects(true)
.verifySsl(true)
.enableCookieManagement(true)
.automaticRetries(true)
.proxy("proxy.com", 8080, "user", "pass");Key config options:
| Method | Impact | Default |
|---|---|---|
| Connection timeout (ms) | 10000 |
| Socket/read timeout (ms) | 60000 |
| Max total connections, max per route | 200/20 |
| Follow HTTP redirects | true |
| Enforce SSL verification | true |
| Accept/store cookies | true |
| Auto-retry on socket errors (up to 4 times) | true |
| Auto-retry on 429/529 with Retry-After header | false |
| Default base URL for all requests | none |
| Register JVM shutdown hook | false |
| Use system properties for proxies etc. | true |
Multiple configurations:
java
// Primary instance (same as static Unirest)
UnirestInstance unirest = Unirest.primaryInstance();
// Spawn a new independent instance
UnirestInstance custom = Unirest.spawnInstance();
custom.config().connectTimeout(3000);⚠️ If you spawn a new instance, YOU are responsible for shutting it down.
See references/configuration.md for full config table, interceptors, object mappers, and metrics.
所有配置均通过 完成:
Unirest.config()java
Unirest.config()
.connectTimeout(5000)
.socketTimeout(10000)
.concurrency(200, 20)
.setDefaultHeader("Accept", "application/json")
.setDefaultBasicAuth("user", "pass")
.followRedirects(true)
.verifySsl(true)
.enableCookieManagement(true)
.automaticRetries(true)
.proxy("proxy.com", 8080, "user", "pass");关键配置项:
| 方法 | 影响 | 默认值 |
|---|---|---|
| 连接超时(毫秒) | 10000 |
| Socket/读取超时(毫秒) | 60000 |
| 最大总连接数、每条路由的最大连接数 | 200/20 |
| 跟随 HTTP 重定向 | true |
| 强制执行 SSL 验证 | true |
| 接受/存储 Cookie | true |
| Socket 错误时自动重试(最多 4 次) | true |
| 遇到 429/529 且包含 Retry-After 请求头时自动重试 | false |
| 所有请求的默认基础 URL | 无 |
| 注册 JVM 关闭钩子 | false |
| 使用系统属性配置代理等 | true |
多实例配置:
java
// Primary instance (same as static Unirest)
UnirestInstance unirest = Unirest.primaryInstance();
// Spawn a new independent instance
UnirestInstance custom = Unirest.spawnInstance();
custom.config().connectTimeout(3000);⚠️ 如果创建新实例,则需要由你负责关闭它。
请参阅 references/configuration.md 获取完整配置表、拦截器、对象映射器和指标。
Critical: Making Requests
关键:发起请求
Basic request types:
java
Unirest.get("http://localhost/users").asString();
Unirest.post("http://localhost/users").body(json).asJson();
Unirest.put("http://localhost/users/1").body(user).asEmpty();
Unirest.delete("http://localhost/users/1").asEmpty();Route parameters:
java
Unirest.get("http://localhost/users/{id}")
.routeParam("id", "42")
.asString();
// Results in http://localhost/users/42Query parameters:
java
Unirest.get("http://localhost/search")
.queryString("q", "unirest")
.queryString("page", 1)
.asString();Headers and auth:
java
Unirest.get("http://localhost/protected")
.header("X-Custom", "value")
.basicAuth("user", "pass")
.asString();Form data:
java
Unirest.post("http://localhost/form")
.field("name", "Alice")
.field("age", 30)
.asEmpty();File upload:
java
Unirest.post("http://localhost/upload")
.field("file", new File("/path/to/file.zip"))
.asEmpty();Async request:
java
CompletableFuture<HttpResponse<JsonNode>> future = Unirest.get("http://localhost/data")
.asJsonAsync(response -> {
System.out.println(response.getBody());
});Per-request proxy (3.x only):
java
Unirest.get("http://localhost/data")
.proxy("proxy.com", 8080)
.asString();JSON Patch (RFC-6902):
java
Unirest.jsonPatch("http://localhost/resource")
.add("/fruits/-", "Apple")
.remove("/bugs")
.replace("/name", "Updated")
.asJson();See references/requests.md for upload progress, paged requests, client certificates, and more.
基础请求类型:
java
Unirest.get("http://localhost/users").asString();
Unirest.post("http://localhost/users").body(json).asJson();
Unirest.put("http://localhost/users/1").body(user).asEmpty();
Unirest.delete("http://localhost/users/1").asEmpty();路由参数:
java
Unirest.get("http://localhost/users/{id}")
.routeParam("id", "42")
.asString();
// Results in http://localhost/users/42查询参数:
java
Unirest.get("http://localhost/search")
.queryString("q", "unirest")
.queryString("page", 1)
.asString();请求头和身份验证:
java
Unirest.get("http://localhost/protected")
.header("X-Custom", "value")
.basicAuth("user", "pass")
.asString();表单数据:
java
Unirest.post("http://localhost/form")
.field("name", "Alice")
.field("age", 30)
.asEmpty();文件上传:
java
Unirest.post("http://localhost/upload")
.field("file", new File("/path/to/file.zip"))
.asEmpty();异步请求:
java
CompletableFuture<HttpResponse<JsonNode>> future = Unirest.get("http://localhost/data")
.asJsonAsync(response -> {
System.out.println(response.getBody());
});单请求代理(仅限 3.x):
java
Unirest.get("http://localhost/data")
.proxy("proxy.com", 8080)
.asString();JSON Patch(RFC-6902):
java
Unirest.jsonPatch("http://localhost/resource")
.add("/fruits/-", "Apple")
.remove("/bugs")
.replace("/name", "Updated")
.asJson();请参阅 references/requests.md 了解上传进度、分页请求、客户端证书等更多信息。
Critical: Handling Responses
关键:处理响应
Response types:
java
// String
String body = Unirest.get(url).asString().getBody();
// Object mapping (GSON included by default)
Book book = Unirest.get(url).asObject(Book.class).getBody();
// Generic types
List<Book> books = Unirest.get(url)
.asObject(new GenericType<List<Book>>(){}).getBody();
// JSON
JsonNode json = Unirest.get(url).asJson().getBody();
// File
File file = Unirest.get(url).asFile("/tmp/download.zip").getBody();
// Empty (status/headers only)
HttpResponse resp = Unirest.delete(url).asEmpty();Error handling:
java
Unirest.get("http://localhost/data")
.asJson()
.ifSuccess(response -> handleSuccess(response))
.ifFailure(response -> {
log.error("Status: " + response.getStatus());
response.getParsingError().ifPresent(e -> {
log.error("Parse error: " + e.getMessage());
});
});Parsing errors:
java
response.getParsingError().ifPresent(ex -> {
String originalBody = ex.getOriginalBody();
String message = ex.getMessage();
});Map error objects:
java
HttpResponse<Book> book = Unirest.get(url).asObject(Book.class);
Error err = book.mapError(Error.class);See references/responses.md for download progress, large responses, body mapping, and more.
响应类型:
java
// String
String body = Unirest.get(url).asString().getBody();
// Object mapping (GSON included by default)
Book book = Unirest.get(url).asObject(Book.class).getBody();
// Generic types
List<Book> books = Unirest.get(url)
.asObject(new GenericType<List<Book>>(){}).getBody();
// JSON
JsonNode json = Unirest.get(url).asJson().getBody();
// File
File file = Unirest.get(url).asFile("/tmp/download.zip").getBody();
// Empty (status/headers only)
HttpResponse resp = Unirest.delete(url).asEmpty();错误处理:
java
Unirest.get("http://localhost/data")
.asJson()
.ifSuccess(response -> handleSuccess(response))
.ifFailure(response -> {
log.error("Status: " + response.getStatus());
response.getParsingError().ifPresent(e -> {
log.error("Parse error: " + e.getMessage());
});
});解析错误:
java
response.getParsingError().ifPresent(ex -> {
String originalBody = ex.getOriginalBody();
String message = ex.getMessage();
});映射错误对象:
java
HttpResponse<Book> book = Unirest.get(url).asObject(Book.class);
Error err = book.mapError(Error.class);请参阅 references/responses.md 了解下载进度、大型响应、请求体映射等更多信息。
Critical: Mocking
关键:模拟
Static mock:
java
MockClient mock = MockClient.register();
mock.expect(HttpMethod.GET, "http://api.example.com/users")
.thenReturn("{\"name\":\"Alice\"}")
.withStatus(200);
String body = Unirest.get("http://api.example.com/users")
.asString().getBody();
// body == "{\"name\":\"Alice\"}"
mock.verifyAll(); // Verify all expects were calledInstance mock (3.x requires both clients):
java
UnirestInstance unirest = Unirest.spawnInstance();
MockClient mock = MockClient.register(unirest);
// In 3.x, the mock implements both Client and AsyncClientBody matching:
java
mock.expect(HttpMethod.POST, "http://api.example.com/users")
.body(FieldMatcher.of("name", "Alice", "role", "admin"))
.thenReturn()
.withStatus(201);Verify with times:
java
var expect = mock.expect(HttpMethod.GET, "http://api.example.com/users").thenReturn();
expect.verify(); // At least once
expect.verify(Times.never()); // Never calledSee references/mocking.md for POJO responses, multiple expects, and more.
静态 mock:
java
MockClient mock = MockClient.register();
mock.expect(HttpMethod.GET, "http://api.example.com/users")
.thenReturn("{\"name\":\"Alice\"}")
.withStatus(200);
String body = Unirest.get("http://api.example.com/users")
.asString().getBody();
// body == "{\"name\":\"Alice\"}"
mock.verifyAll(); // Verify all expects were called实例 mock(3.x 需要同时注册两个客户端):
java
UnirestInstance unirest = Unirest.spawnInstance();
MockClient mock = MockClient.register(unirest);
// In 3.x, the mock implements both Client and AsyncClient请求体匹配:
java
mock.expect(HttpMethod.POST, "http://api.example.com/users")
.body(FieldMatcher.of("name", "Alice", "role", "admin"))
.thenReturn()
.withStatus(201);按次数验证:
java
var expect = mock.expect(HttpMethod.GET, "http://api.example.com/users").thenReturn();
expect.verify(); // At least once
expect.verify(Times.never()); // Never called请参阅 references/mocking.md 了解 POJO 响应、多个预期请求等更多信息。
Critical: Caching
关键:缓存
Basic caching:
java
Unirest.config().cacheResponses(true);Advanced caching with options:
java
Unirest.config().cacheResponses(Cache.builder()
.depth(100) // Max entries
.maxAge(5, TimeUnit.MINUTES)); // Entry TTLCustom cache (e.g., Guava):
java
Unirest.config().cacheResponses(
Cache.builder().backingCache(new MyGuavaCache()));See references/caching.md for custom cache implementation details.
基础缓存:
java
Unirest.config().cacheResponses(true);使用选项的高级缓存:
java
Unirest.config().cacheResponses(Cache.builder()
.depth(100) // Max entries
.maxAge(5, TimeUnit.MINUTES)); // Entry TTL自定义缓存(例如 Guava):
java
Unirest.config().cacheResponses(
Cache.builder().backingCache(new MyGuavaCache()));请参阅 references/caching.md 了解自定义缓存实现的详细信息。
Critical: Proxies
关键:代理
Simple proxy:
java
Unirest.config().proxy("proxy.com", 8080, "user", "pass");Per-request proxy (3.x only):
java
Unirest.get("http://localhost/data")
.proxy("proxy.com", 8080)
.asString();System properties (default: true in 3.x):
java
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "7777");
// useSystemProperties defaults to true in 3.xSee references/proxies.md for details.
简单代理:
java
Unirest.config().proxy("proxy.com", 8080, "user", "pass");单请求代理(仅限 3.x):
java
Unirest.get("http://localhost/data")
.proxy("proxy.com", 8080)
.asString();系统属性(3.x 中默认值为 true):
java
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "7777");
// useSystemProperties defaults to true in 3.x请参阅 references/proxies.md 了解详细信息。
Quick Fixes
快速修复
| Error | Cause | Fix |
|---|---|---|
| Wrong package | Use |
| Response parsing failed | Check |
| Server unreachable or timeout too low | Increase |
| Read timeout exceeded | Increase |
| SSL verification failure | Use |
| Proxy not working | System props may be disabled | Check |
| Too many connections | Connection pool exhausted | Increase |
| Automatic retries not working | Disabled or not applicable | Check |
| 错误 | 原因 | 修复方法 |
|---|---|---|
| 包名错误 | 使用 |
| 响应解析失败 | 检查 |
| 无法访问服务器或超时时间过短 | 增加 |
| 读取超时 | 增加 |
| SSL 验证失败 | 仅在开发环境中使用 |
| 代理不工作 | 系统属性可能已禁用 | 检查 |
| 连接数过多 | 连接池已耗尽 | 增加 |
| 自动重试不工作 | 已禁用或不适用 | 检查 |
Gotchas
易踩坑事项
- Java 8+ is sufficient — 3.x runs on Java 8 (unlike 4.x which requires Java 11+)
- GSON included by default — No need to declare a separate JSON module (unlike 4.x)
- Package is — Not
kong.unirest(that's 4.x)kong.unirest.core - Single Maven dependency — (unlike 4.x which uses BOM + core + module)
unirest-java:3.14.5 - Apache HttpClient engine — Uses Apache HttpClient 4 (not java.net.http.HttpClient)
- Socket timeout is independent — controls read timeout separately from
socketTimeout()connectTimeout() - Connection pool tuning — lets you tune Apache's connection pool
concurrency(total, perRoute) - Automatic retries enabled by default — retries socket errors up to 4 times
automaticRetries(true) - Per-request proxies supported — works (removed in 4.x)
request.proxy(host, port) - HostnameVerifier supported — for custom SSL hostname verification
hostnameVerifier(verifier) - Shutdown hooks available — registers JVM shutdown hooks
addShutdownHook(true) - System proxy props enabled by default — defaults to
useSystemProperties(unlike 4.x)true - No WebSocket via Unirest — Use Apache HttpClient WebSocket or a dedicated library
- No SSE support — does not exist in 3.x
Unirest.sse() - Mock registration requires both clients — MockClient implements both and
ClientAsyncClient
- Java 8+ 已足够 — 3.x 可在 Java 8 上运行(不同于要求 Java 11+ 的 4.x)
- 默认包含 GSON — 无需声明单独的 JSON 模块(不同于 4.x)
- 包名为 — 不是
kong.unirest(后者属于 4.x)kong.unirest.core - 单个 Maven 依赖 — (不同于使用 BOM + core + module 的 4.x)
unirest-java:3.14.5 - Apache HttpClient 引擎 — 使用 Apache HttpClient 4(而不是 java.net.http.HttpClient)
- Socket 超时彼此独立 — 单独控制读取超时,与
socketTimeout()分开connectTimeout() - 连接池调优 — 可调整 Apache 的连接池
concurrency(total, perRoute) - 默认启用自动重试 — 会在 socket 错误时最多重试 4 次
automaticRetries(true) - 支持单请求代理 — 可用(4.x 中已移除)
request.proxy(host, port) - 支持 HostnameVerifier — 用于自定义 SSL 主机名验证
hostnameVerifier(verifier) - 可使用关闭钩子 — 注册 JVM 关闭钩子
addShutdownHook(true) - 默认启用系统代理属性 — 默认为
useSystemProperties(不同于 4.x)true - Unirest 不支持 WebSocket — 使用 Apache HttpClient WebSocket 或专用库
- 不支持 SSE — 3.x 中不存在
Unirest.sse() - Mock 注册需要两个客户端 — MockClient 同时实现 和
ClientAsyncClient
References
参考资料
Requests
请求
- requests.md — Route params, query params, headers, auth, body types, file uploads, upload progress, async, paged requests, per-request proxy
- requests.md — 路由参数、查询参数、请求头、身份验证、请求体类型、文件上传、上传进度、异步、分页请求、单请求代理
Responses
响应
- responses.md — asEmpty/asString/asObject/asJson/asFile, GenericType, parsing errors, error object mapping, download progress, large responses, error handling
- responses.md — asEmpty/asString/asObject/asJson/asFile、GenericType、解析错误、错误对象映射、下载进度、大型响应、错误处理
Configuration
配置
- configuration.md — Full config options table, global interceptors, multiple configurations, object mappers, metrics, Apache-specific options
- configuration.md — 完整配置项表、全局拦截器、多实例配置、对象映射器、指标、Apache 特有选项
Mocking
Mock
- mocking.md — Static/instance mocks, multiple expects (scoring), verification, body matching, form params, POJO responses
- mocking.md — 静态/实例 mock、多个预期请求(评分)、验证、请求体匹配、表单参数、POJO 响应
Caching
缓存
- caching.md — Basic/advanced caching, custom cache implementations
- caching.md — 基础/高级缓存、自定义缓存实现
Proxies
代理
- proxies.md — Simple proxy, system properties, per-request proxy
- proxies.md — 简单代理、系统属性、单请求代理