Call the Anthropic Claude API from Java using the official SDK or the Java HttpClient. Complete examples for text generation, streaming, and tool use in Java 11+.
Anthropic ships official SDKs for Python, TypeScript, and Go. For Java, the cleanest path is the REST API via java.net.http.HttpClient (Java 11+). The examples below wrap this in a reusable utility class.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
import com.google.gson.*;
import java.net.URI;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
public class ClaudeClient {
private static final String API_URL = "https://api.anthropic.com/v1/messages";
private static final String API_KEY = System.getenv("ANTHROPIC_API_KEY");
private static final String MODEL = "claude-sonnet-4-6-20251001";
private final HttpClient http = HttpClient.newHttpClient();
private final Gson gson = new Gson();
public String chat(String userMessage) throws Exception {
JsonObject body = new JsonObject();
body.addProperty("model", MODEL);
body.addProperty("max_tokens", 1024);
JsonArray messages = new JsonArray();
JsonObject msg = new JsonObject();
msg.addProperty("role", "user");
JsonArray content = new JsonArray();
JsonObject textBlock = new JsonObject();
textBlock.addProperty("type", "text");
textBlock.addProperty("text", userMessage);
content.add(textBlock);
msg.add("content", content);
messages.add(msg);
body.add("messages", messages);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.header("x-api-key", API_KEY)
.header("anthropic-version", "2023-06-01")
.POST(HttpRequest.BodyPublishers.ofString(gson.toJson(body)))
.build();
HttpResponse<String> response = http.send(request, BodyHandlers.ofString());
if (response.statusCode() != 200)
throw new RuntimeException("API error " + response.statusCode() + ": " + response.body());
JsonObject resp = JsonParser.parseString(response.body()).getAsJsonObject();
return resp.getAsJsonArray("content")
.get(0).getAsJsonObject()
.get("text").getAsString();
}
public static void main(String[] args) throws Exception {
ClaudeClient client = new ClaudeClient();
System.out.println(client.chat("Explain Java virtual threads in two sentences."));
}
}
public CompletableFuture<String> chatAsync(String userMessage) {
JsonObject body = buildBody(userMessage);
HttpRequest request = buildRequest(body);
return http.sendAsync(request, BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200)
throw new RuntimeException("API error " + response.statusCode());
return extractText(response.body());
});
}
public String chatWithRetry(String userMessage, int maxRetries) throws Exception {
int attempt = 0;
while (true) {
HttpResponse<String> response = http.send(buildRequest(buildBody(userMessage)), BodyHandlers.ofString());
int status = response.statusCode();
if (status == 200) return extractText(response.body());
if ((status == 429 || status >= 500) && attempt++ < maxRetries) {
Thread.sleep((long) Math.pow(2, attempt) * 1000L);
continue;
}
throw new RuntimeException("Non-retryable error " + status);
}
}
| Model ID | Best for | Input ($/1M) | Output ($/1M) |
|---|---|---|---|
claude-haiku-4-5-20251001 | High-throughput, low-cost tasks | $0.80 | $4.00 |
claude-sonnet-4-6-20251001 | Balanced intelligence + speed | $3.00 | $15.00 |
claude-opus-4-7-20251001 | Most capable, complex reasoning | $15.00 | $75.00 |
Estimate costs for your Java workload at the Claude API Cost Calculator.