MCPInstall

unirest-java-4

Unirest-Java 4.x HTTP client library for Java 11+. Use when making HTTP requests (GET/POST/PUT/DELETE), building REST API clients, handling JSON responses, file uploads/downloads, async requests, Server-Sent Events (SSE), mocking HTTP calls for testing, configuring proxies, or caching responses. Covers Unirest 4.x (requires Java 11+, modular dependencies, kong.unirest.core package) with GSON/Jackson object mapping, request/response interceptors, and migration from Unirest 3.x.

Installs
77
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/full-stack-skills/java-skills --skill unirest-java-4
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads unirest-java-4 automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Unirest-Java 4.x Reference (v4.10.0)

This skill covers the Unirest-Java 4.x HTTP client library for Java 11+. It uses the built-in java.net.http.HttpClient (replacing Apache HttpClient in 3.x) and defaults to HTTP/2.

Capability Boundaries

✅ Strong Suits

  1. Building HTTP requests (GET, POST, PUT, DELETE, PATCH) with fluent API
  2. JSON/object mapping with GSON or Jackson (must declare module explicitly)
  3. Async requests with CompletableFuture (built into java.net.http.HttpClient)
  4. File uploads with progress monitoring
  5. Server-Sent Events (SSE) consumption via Unirest.sse(url)
  6. WebSocket connections via Unirest.webSocket(url)
  7. Mock testing for HTTP clients
  8. Response caching with configurable eviction
  9. Proxy configuration (simple, system, ProxySelector)
  10. HTTP/2 by default (configurable via config.version())
  11. Custom executor support via config.executor()
  12. Java Authenticator support via config.authenticator()

⚠️ Requirements

  1. Java 11 or higher (uses java.net.http.HttpClient)
  2. Must declare a JSON module (unirest-modules-gson or unirest-modules-jackson) for object mapping
  3. Maven/Gradle dependency management with BOM

❌ Out of Scope (with alternatives)

  1. Per-request proxies → use global Unirest.config().proxy() (removed in 4.x)
  2. Custom HostnameVerifier → use disableHostNameVerification() system property
  3. Socket timeout (independent of connect timeout) → use requestTimeout() instead
  4. Connection pool tuning (concurrency(total, perRoute)) → not supported (java.net.http manages this)
  5. Automatic retries on socket errors → use retryAfter() for 429/529 only
  6. Shutdown hooks → not needed (no background threads to manage)
  7. Apache HttpClient integration → use 3.x if you need Apache-specific features

When to Use This Skill

Use this skill when the user needs to:

  • Make HTTP requests to REST APIs in Java
  • Upload or download files via HTTP
  • Consume Server-Sent Event streams
  • Mock HTTP calls in unit tests
  • Configure proxies for HTTP requests
  • Cache HTTP responses
  • Migrate from Unirest 3.x to 4.x

Quick Start

Maven dependency (Unirest 4.10.0):

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.konghq</groupId>
            <artifactId>unirest-java-bom</artifactId>
            <version>4.10.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-java-core</artifactId>
    </dependency>
    <!-- Choose ONE JSON module: -->
    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-modules-gson</artifactId>
    </dependency>
</dependencies>

Minimal GET request:

String body = Unirest.get("https://api.example.com/users")
    .asString()
    .getBody();

Minimal POST with JSON:

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 4 is modular. You must declare:

  1. unirest-java-core — the HTTP client engine
  2. A JSON module — unirest-modules-gson OR unirest-modules-jackson (required for object mapping/JSON parsing)

⚠️ Without a JSON module, calls to asObject(), asJson(), and JSON Patch will fail at runtime.

See references/configuration.md for full installation details.

Critical: Configuration

All configuration goes through Unirest.config():

Unirest.config()
    .connectTimeout(5000)
    .setDefaultHeader("Accept", "application/json")
    .setDefaultBasicAuth("user", "pass")
    .followRedirects(true)
    .verifySsl(true)
    .enableCookieManagement(true)
    .proxy("proxy.com", 8080, "user", "pass");

Key config options:

MethodImpactDefault
connectTimeout(int)Connection timeout (ms)10000
requestTimeout(int)Request timeout (ms)infinite
followRedirects(boolean)Follow HTTP redirectstrue
verifySsl(boolean)Enforce SSL verificationtrue
enableCookieManagement(boolean)Accept/store cookiestrue
retryAfter(boolean)Auto-retry on 429/529false
defaultBaseUrl(String)Default base URL for all requestsnone

Multiple configurations:

// 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.

Critical: Making Requests

Basic request types:

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:

Unirest.get("http://localhost/users/{id}")
    .routeParam("id", "42")
    .asString();
// Results in http://localhost/users/42

Query parameters:

Unirest.get("http://localhost/search")
    .queryString("q", "unirest")
    .queryString("page", 1)
    .asString();

Headers and auth:

Unirest.get("http://localhost/protected")
    .header("X-Custom", "value")
    .basicAuth("user", "pass")
    .asString();

Form data:

Unirest.post("http://localhost/form")
    .field("name", "Alice")
    .field("age", 30)
    .asEmpty();

File upload:

Unirest.post("http://localhost/upload")
    .field("file", new File("/path/to/file.zip"))
    .asEmpty();

Async request:

CompletableFuture<HttpResponse<JsonNode>> future = Unirest.get("http://localhost/data")
    .asJsonAsync(response -> {
        System.out.println(response.getBody());
    });

JSON Patch (RFC-6902):

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.

Critical: Handling Responses

Response types:

// String
String body = Unirest.get(url).asString().getBody();

// Object mapping
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:

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:

response.getParsingError().ifPresent(ex -> {
    String originalBody = ex.getOriginalBody();
    String message = ex.getMessage();
});

Map error objects:

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.

Critical: Server-Sent Events (SSE)

Async SSE consumption:

var future = Unirest.sse("https://stream.example.com/events")
    .connect(event -> {
        var data = event.asObject(MyEvent.class);
        System.out.println("Event: " + data.getTitle());
    });

Synchronous SSE consumption:

Unirest.sse("https://stream.example.com/events")
    .connect()
    .map(event -> event.asObject(MyEvent.class))
    .forEach(data -> System.out.println("Event: " + data.getTitle()));

⚠️ SSE connections are persistent. Use async mode in production systems. ⚠️ Object mapping requires an ObjectMapper to be configured.

See references/sse.md for full details.

Critical: Caching

Basic caching:

Unirest.config().cacheResponses(true);

Advanced caching with options:

Unirest.config().cacheResponses(Cache.builder()
    .depth(100)                      // Max entries
    .maxAge(5, TimeUnit.MINUTES));   // Entry TTL

Custom cache (e.g., Guava):

Unirest.config().cacheResponses(
    Cache.builder().backingCache(new MyGuavaCache()));

See references/caching.md for custom cache implementation details.

Critical: Mocking

Static mock:

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

Instance mock:

UnirestInstance unirest = Unirest.spawnInstance();
MockClient mock = MockClient.register(unirest);

Body matching:

mock.expect(HttpMethod.POST, "http://api.example.com/users")
    .body(FieldMatcher.of("name", "Alice", "role", "admin"))
    .thenReturn()
    .withStatus(201);

Verify with times:

var expect = mock.expect(HttpMethod.GET, "http://api.example.com/users").thenReturn();
expect.verify();              // At least once
expect.verify(Times.never()); // Never called

See references/mocking.md for POJO responses, multiple expects, and more.

Critical: Proxies

Simple proxy:

Unirest.config().proxy("proxy.com", 8080, "user", "pass");

System properties:

System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "7777");
Unirest.config().useSystemProperties(true);

Multiple proxies (ProxySelector):

Unirest.config()
    .proxy(new ProxySelector() {
        @Override
        public List<Proxy> select(URI uri) {
            if (uri.getHost().equals("internal.com")) {
                return List.of(new Proxy(HTTP,
                    InetSocketAddress.createUnresolved("internal-proxy.com", 8080)));
            }
            return List.of(new Proxy(HTTP,
                InetSocketAddress.createUnresolved("default-proxy.com", 8080)));
        }
        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
    });

See references/proxies.md for authenticator setup and details.

Critical: WebSocket

Connect to a WebSocket:

Unirest.webSocket("ws://localhost/socket")
    .connect(ws -> {
        ws.sendText("Hello!");
        ws.onMessage(message -> {
            System.out.println("Received: " + message);
        });
    });

WebSocket with POJO mapping:

Unirest.webSocket("ws://localhost/events")
    .connect(ws -> {
        ws.onMessage(event -> {
            MyEvent data = event.asObject(MyEvent.class);
            processEvent(data);
        });
    });

⚠️ WebSocket is a 4.x-only feature. Not available in 3.x.

See references/websocket.md for full details.

Quick Fixes

ErrorCauseFix
NoClassDefFoundError: JsonObjectMissing JSON moduleAdd unirest-modules-gson or unirest-modules-jackson dependency
java.lang.NoClassDefFoundError: kong/unirest/UnirestWrong package in 4.xChange import from kong.unirest.* to kong.unirest.core.*
asObject() returns null bodyResponse parsing failedCheck response.getParsingError() for details
ConnectException: Connection timed outServer unreachable or timeout too lowIncrease connectTimeout or check network
SSLHandshakeExceptionSSL verification failureUse verifySsl(false) for dev only, fix certs in prod
Host header override not allowedJava 11+ HttpClient restrictionSet system property jdk.httpclient.allowRestrictedHeaders=host
Proxy not working in 4.xSystem props disabled by default in 4.xCall useSystemProperties(true) explicitly

Gotchas

  1. Java 11+ is mandatory — Unirest 4.x uses java.net.http.HttpClient and will not run on Java 8
  2. JSON module must be declared — Unlike 3.x, 4.x has NO default JSON parser. Without unirest-modules-gson or unirest-modules-jackson, JSON parsing will fail at runtime
  3. Package rename — kong.unirest (3.x) → kong.unirest.core (4.x), JSON modules at kong.unirest.modules.gson/jackson (4.3+)
  4. HTTP/2 by default — 4.x defaults to HttpClient.Version.HTTP_2. Use config.version(HttpClient.Version.HTTP_1_1) to downgrade
  5. No per-request proxies — 3.x allowed request.proxy(host, port). 4.x only supports global proxy via Unirest.config().proxy()
  6. No socketTimeout — 3.x had independent socketTimeout(). 4.x uses requestTimeout() which covers the entire request lifecycle
  7. No concurrency tuning — concurrency(total, perRoute) was Apache-specific. java.net.http manages connection pools internally
  8. No automatic retries — automaticRetries(true) was Apache-specific. 4.x only has retryAfter() for 429/529 responses
  9. No HostnameVerifier — 3.x had hostnameVerifier(verifier). 4.x uses disableHostNameVerification() system property (JVM-wide)
  10. System proxy props disabled by default — Unlike 3.x (default true), 4.x defaults useSystemProperties to false
  11. SSE and WebSocket are 4.x-only — Unirest.sse() and Unirest.webSocket() do not exist in 3.x
  12. Mock registration simplified — 3.x: MockClient.register() required .httpClient(client).asyncClient(client). 4.x: only .httpClient(client)
  13. Config changes require reset — Once Unirest is activated, changing client-creation config requires config().reset() first
  14. isRunning() removed — 3.x had Unirest.isRunning(). 4.x removed it (no background threads to monitor)

References

Requests

  • requests.md — Route params, query params, headers, auth, body types, file uploads, upload progress, async, paged requests, client certificates

Responses

  • responses.md — asEmpty/asString/asObject/asJson/asFile, GenericType, parsing errors, error object mapping, download progress, large responses, error handling

Configuration

  • configuration.md — Full config options table, global interceptors, multiple configurations, object mappers (Jackson/GSON), metrics

Mocking

  • mocking.md — Static/instance mocks, multiple expects (scoring), verification, body matching, form params, POJO responses

Caching

  • caching.md — Basic/advanced caching, custom cache implementations

Server-Sent Events

  • sse.md — Async/sync SSE consumption, object mapping requirements

WebSocket

  • websocket.md — WebSocket connections, message handling, POJO mapping

Proxies

  • proxies.md — Simple proxy, system properties, ProxySelector with Authenticator

Upgrade Guide

  • upgrade-guide.md — 3.x→4.x migration, package renames, Maven coordinate changes, behavior differences

FAQ

What does the unirest-java-4 skill do?

Unirest-Java 4.x HTTP client library for Java 11+. Use when making HTTP requests (GET/POST/PUT/DELETE), building REST API clients, handling JSON responses, file uploads/downloads, async requests, Server-Sent Events (SSE), mocking HTTP calls for testing, configuring proxies, or caching responses. Covers Unirest 4.x (requires Java 11+, modular dependencies, kong.unirest.core package) with GSON/Jackson object mapping, request/response interceptors, and migration from Unirest 3.x.

How do I install unirest-java-4?

Run npx skills add https://github.com/full-stack-skills/java-skills --skill unirest-java-4 in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/unirest-java-4/ (personal) or .claude/skills/unirest-java-4/ (project).

Which AI agents can use unirest-java-4?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is unirest-java-4 safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains unirest-java-4?

It is published by full-stack-skills in full-stack-skills/java-skills. It has 77 recorded installs.

More from full-stack-skills/java-skills

View all →

java-development-manual

full-stack-skills/java-skills

Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设计 (7) 工程架构设计时使用此skill。 触发词:Java规范、阿里规约、代码规范、开发手册、编程规约、异常处理、单元测试、安全、MySQL、工程结构、设计模式。

Backend & APIs119 installs

mybatis-plus-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs114 installs

java-code-comments

full-stack-skills/java-skills

Provides comprehensive guidance for adding Java code comments following industry standards and best practices. This skill helps add class-level comments, method-level comments, and field-level comments to Java code. Use when the user wants to add comments to Java code, needs to document Java classes/methods/fields, wants to improve code documentation, or needs to generate JavaDoc comments. This skill covers Controller, Service, ServiceImpl, Mapper, Model, Entity, BO (Business Object), DTO, VO, and other common Java component types. The skill follows a systematic workflow: scan codebase, identify components, create todo list, and add comments in order (class comments → method comments → field comments).

Backend & APIs112 installs

java-conventions

full-stack-skills/java-skills

统一 Java 项目编码规范与注释规范(SLF4J+Lombok 日志、Bean Lombok 注解选择、判空 Objects/Optional、工具类优先级 Spring→Apache Commons→Hutool→Guava、复杂逻辑用设计模式/简单逻辑不拆分、Controller/Service/ServiceImpl/Mapper 注释一致性)。当需要“按 Java 规范重构/Review/补全注释/统一日志/统一工具类使用/补全 JavaDoc”时使用。

Backend & APIs108 installs

mybatis-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs102 installs

mapstruct-patterns

full-stack-skills/java-skills

MapStruct 最佳实践模式。从官方 Reference Guide 提炼,覆盖 Mapper 三种定义方式(接口/抽象类/default方法)、Spring 注入策略(CONSTRUCTOR推荐/SETTER解决循环依赖)、嵌套映射模式(显式子方法 dot notation 一次性配置)、@Qualifier @Named 的安全选择、Lombok 集成规则、@MappingComposition 谨慎使用。 纠正 LLM 最常见的错误:用反射 BeanUtils 而非编译期 MapStruct、嵌套映射全写在一个方法、不知 SETTER 解决循环依赖。

Backend & APIs97 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs