Loading...
Loading...
Unirest-Java 3.x HTTP client library for Java 8+. Use when making HTTP requests (GET/POST/PUT/DELETE), building REST API clients, handling JSON responses, file uploads/downloads, async requests, mocking HTTP calls for testing, configuring proxies, or caching responses. Covers Unirest 3.x (Apache HttpClient based, default GSON included, kong.unirest package) with object mapping, request/response interceptors, and migration guidance.
npx skill4agent add full-stack-skills/java-skills unirest-java-3concurrency(total, perRoute)automaticRetries()concurrency()<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.
String body = Unirest.get("https://api.example.com/users")
.asString()
.getBody();HttpResponse<JsonNode> response = Unirest.post("https://api.example.com/users")
.header("Content-Type", "application/json")
.body(new User("Alice", "alice@example.com"))
.asJson();<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.config()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");| 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 |
// 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.
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();Unirest.get("http://localhost/users/{id}")
.routeParam("id", "42")
.asString();
// Results in http://localhost/users/42Unirest.get("http://localhost/search")
.queryString("q", "unirest")
.queryString("page", 1)
.asString();Unirest.get("http://localhost/protected")
.header("X-Custom", "value")
.basicAuth("user", "pass")
.asString();Unirest.post("http://localhost/form")
.field("name", "Alice")
.field("age", 30)
.asEmpty();Unirest.post("http://localhost/upload")
.field("file", new File("/path/to/file.zip"))
.asEmpty();CompletableFuture<HttpResponse<JsonNode>> future = Unirest.get("http://localhost/data")
.asJsonAsync(response -> {
System.out.println(response.getBody());
});Unirest.get("http://localhost/data")
.proxy("proxy.com", 8080)
.asString();Unirest.jsonPatch("http://localhost/resource")
.add("/fruits/-", "Apple")
.remove("/bugs")
.replace("/name", "Updated")
.asJson();// 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();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());
});
});response.getParsingError().ifPresent(ex -> {
String originalBody = ex.getOriginalBody();
String message = ex.getMessage();
});HttpResponse<Book> book = Unirest.get(url).asObject(Book.class);
Error err = book.mapError(Error.class);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 calledUnirestInstance unirest = Unirest.spawnInstance();
MockClient mock = MockClient.register(unirest);
// In 3.x, the mock implements both Client and AsyncClientmock.expect(HttpMethod.POST, "http://api.example.com/users")
.body(FieldMatcher.of("name", "Alice", "role", "admin"))
.thenReturn()
.withStatus(201);var expect = mock.expect(HttpMethod.GET, "http://api.example.com/users").thenReturn();
expect.verify(); // At least once
expect.verify(Times.never()); // Never calledUnirest.config().cacheResponses(true);Unirest.config().cacheResponses(Cache.builder()
.depth(100) // Max entries
.maxAge(5, TimeUnit.MINUTES)); // Entry TTLUnirest.config().cacheResponses(
Cache.builder().backingCache(new MyGuavaCache()));Unirest.config().proxy("proxy.com", 8080, "user", "pass");Unirest.get("http://localhost/data")
.proxy("proxy.com", 8080)
.asString();System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "7777");
// useSystemProperties defaults to true in 3.x| 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 |
kong.unirestkong.unirest.coreunirest-java:3.14.5socketTimeout()connectTimeout()concurrency(total, perRoute)automaticRetries(true)request.proxy(host, port)hostnameVerifier(verifier)addShutdownHook(true)useSystemPropertiestrueUnirest.sse()ClientAsyncClient