← Blog

Claude API Java Integration Example: A Working Guide

2026-11-13 · 4 min read · SubToAPI Team

Anthropic doesn't ship an official Java SDK, which is why "claude api java integration example" is such a common search. The good news is that you don't need one — the Claude API is a plain HTTPS/JSON REST API, and Java's built-in java.net.http.HttpClient (available since Java 11) can call it directly with no third-party HTTP library.

This article walks through a working Java integration: sending a request, parsing the JSON response, handling streaming, and dealing with the headers Anthropic requires. It also covers a simpler path if you want to skip header and key management entirely.

What you need before writing any code

Add Jackson to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
</dependency>

Calling the Messages API directly

The core Claude endpoint is POST /v1/messages. In Java, that looks like this:

import java.net.URI;
import java.net.http.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class ClaudeClient {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        ObjectNode message = mapper.createObjectNode();
        message.put("role", "user");
        message.put("content", "Explain checked exceptions in two sentences.");

        ObjectNode body = mapper.createObjectNode();
        body.put("model", "claude-3-5-sonnet-latest");
        body.put("max_tokens", 300);
        body.putArray("messages").add(message);

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.anthropic.com/v1/messages"))
                .header("x-api-key", System.getenv("ANTHROPIC_API_KEY"))
                .header("anthropic-version", "2023-06-01")
                .header("content-type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
                .build();

        HttpResponse<String> response = client.send(
                request, HttpResponse.BodyHandlers.ofString());

        JsonNode json = mapper.readTree(response.body());
        System.out.println(json.get("content").get(0).get("text").asText());
    }
}

This is the entire integration. No SDK, no reflection, no annotation magic — just an HttpRequest built with the right headers and a JSON body parsed on the way back.

Why the headers matter

Two headers are easy to miss and cause the most support tickets:

If you forget either, you'll get a 4xx response with a JSON error body rather than a thrown exception, so always check response.statusCode() before parsing content.

Handling streaming responses in Java

Claude supports server-sent events (SSE) for streaming. With raw HttpClient, you consume the response as a line stream instead of a single string:

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.anthropic.com/v1/messages"))
        .header("x-api-key", System.getenv("ANTHROPIC_API_KEY"))
        .header("anthropic-version", "2023-06-01")
        .header("content-type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(streamingBody))
        .build();

HttpResponse<Stream<String>> response = client.send(
        request, HttpResponse.BodyHandlers.ofLines());

response.body()
        .filter(line -> line.startsWith("data:"))
        .forEach(line -> {
            String payload = line.substring(5).trim();
            if (!payload.equals("[DONE]")) {
                System.out.print(parseDeltaText(payload));
            }
        });

parseDeltaText just extracts the text field from content_block_delta events using Jackson. It's more code than a Python or Node SDK would need, but it's not complicated — it's line-by-line SSE parsing, which Java handles natively.

Retries and timeouts

Production Java code should set explicit timeouts and retry on 429/5xx responses:

HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build();

HttpRequest request = HttpRequest.newBuilder()
        .uri(uri)
        .timeout(Duration.ofSeconds(60))
        // ... headers and body
        .build();

Wrap the call in a small retry loop with exponential backoff for 429 and 529 (overloaded) responses — Anthropic's rate limits return these codes rather than throwing a connection-level error.

A simpler option: one HTTPS endpoint, no key juggling

If part of what's slowing down your Java integration is managing anthropic-version headers, rotating keys per environment, or tracking usage across a team, SubToAPI turns your existing Claude access into a standard HTTPS API with application keys (sub_live_...). The request shape is the same Messages format, so the Java code above barely changes — you swap the host and use a single Authorization: Bearer header:

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.subtoapi.app/v1/messages"))
        .header("Authorization", "Bearer " + System.getenv("SUBTOAPI_KEY"))
        .header("content-type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
        .build();

That's useful for Java teams running multiple services or environments, since you get per-key usage metadata and team seats in one dashboard instead of sharing a single raw API key across services. See the quickstart and Messages API reference for the full request/response shape, and streaming docs if you're building the SSE consumer above. Plans start at €9/month on the pricing page, with a free trial at signup.

Keeping the integration maintainable

A few practices that help once this code is in a real codebase:

Questions

Is there an official Claude Java SDK? No. Anthropic maintains official SDKs for Python and TypeScript. Java developers call the REST API directly with HttpClient or a library like OkHttp — this is fully supported and used in production.

What Java version do I need? Java 11+ for the built-in HttpClient. Earlier versions work too if you use OkHttp or Apache HttpClient instead, since the integration is just standard HTTPS and JSON.

Can I use Spring Boot with the Claude API? Yes — inject RestClient or WebClient (Spring 6+) configured with the same headers and endpoint shown above. The integration pattern doesn't change; Spring just manages the HTTP client lifecycle for you.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →