Calling LLMs from Java: HTTP, JSON & Streaming
This is post 2 of 10 in the AI for Java Developers track — Java-first, hype-free AI integration. New to the series? Start at the Java Learning Roadmap 2026 hub.
The customer problem
Your company's support team drowns in long customer threads — fifty-message email chains where the actual issue hides somewhere in the middle. They ask you, the Java developer, for an internal tool: paste a thread in, get a short summary out. No new framework, no microservice sprawl — just call a chat API from the Java service you already run.
That means this post is about plumbing, not magic: how to send an HTTP request to a chat API, shape it correctly, parse the answer, survive the ways it fails, and stream tokens so the UI doesn't sit silent for twenty seconds. By the end you'll have one complete, copy-pasteable client class you can actually run.
OPENAI_API_KEY environment variable. Every sample output below is labeled ILLUSTRATIVE — invented for this example, not a measured API response. Anything volatile (model names, pricing, rate limits): check the provider's current docs.The request shape: messages, roles, model, temperature
A chat API's core endpoint accepts a JSON body with three essential fields:
{
"model": "gpt-4o-mini",
"messages": [
{ "role": "system", "content": "You summarize customer support threads for the support team. Reply in under 120 words." },
{ "role": "user", "content": "Summarize this thread:\n\n[2026-10-13 09:12] Customer: ..." }
],
"temperature": 0.3
}
model— which model serves the request. Names change; treat them as configuration, never hard-code assumptions about which is "best".messages— the conversation. Each entry has arole(systemsets behavior,usercarries the task,assistantreplays prior replies for multi-turn chats) andcontent. Order matters: the model reads them as a conversation.temperature— controls sampling randomness, typically 0 to 2. High values make output more varied; low values make it more focused. Temperature is not a determinism knob: even attemperature: 0, distributed systems can return different completions across calls. If you need reproducible results, temperature 0 helps, but never promise exact repeatability — that's what evals and pinned model versions are for.
Sending it with java.net.http.HttpClient
Java 11+'s HttpClient is all you need — no framework, no extra HTTP library. Jackson handles JSON (Maven: com.fasterxml.jackson.core:jackson-databind — check the current version in your build tool's central repository).
First, the DTOs as records and a typed exception so callers can react to failure modes instead of catching Exception:
package com.example.ai;
/** One message in the conversation. Role is "system", "user", or "assistant". */
public record ChatMessage(String role, String content) { }
package com.example.ai;
/** A classified failure from the LLM API: auth, rate-limited, bad-request, or http-<status>. */
public final class LlmException extends Exception {
private final String code;
public LlmException(String code, String message) {
super(message);
this.code = code;
}
public String code() {
return code;
}
}
The complete client class
One class, three operations: a plain chat call, a retrying variant, and a streaming variant. Timeouts are set on both connect and request — an HTTP call without a timeout is a thread you'll never get back.
package com.example.ai;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
public final class LlmClient {
private static final String DEFAULT_BASE_URL = "https://api.openai.com/v1";
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(60);
private final HttpClient http;
private final ObjectMapper json;
private final String baseUrl;
private final String apiKey;
/** Reads the key from the OPENAI_API_KEY environment variable. */
public LlmClient() {
this(requireApiKey(), DEFAULT_BASE_URL);
}
public LlmClient(String apiKey, String baseUrl) {
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalArgumentException("API key must not be blank");
}
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.json = new ObjectMapper();
this.http = HttpClient.newBuilder()
.connectTimeout(CONNECT_TIMEOUT)
.build();
}
private static String requireApiKey() {
String key = System.getenv("OPENAI_API_KEY");
if (key == null || key.isBlank()) {
throw new IllegalStateException(
"Set the OPENAI_API_KEY environment variable before running.");
}
return key;
}
/** Single chat call. Throws LlmException with a code callers can switch on. */
public String chat(String model, List<ChatMessage> messages, double temperature)
throws IOException, InterruptedException, LlmException {
String body = json.writeValueAsString(Map.of(
"model", model,
"messages", messages,
"temperature", temperature));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/chat/completions"))
.timeout(REQUEST_TIMEOUT)
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response =
http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() / 100 != 2) {
throw toException(response.statusCode(), response.body());
}
JsonNode root = json.readTree(response.body());
JsonNode content = root.path("choices").path(0).path("message").path("content");
if (content.isMissingNode() || content.isNull()) {
throw new LlmException("unexpected-response",
"Response had no choices[0].message.content");
}
return content.asText();
}
/** Retries transient rate-limit (429) failures with exponential backoff. */
public String chatWithRetry(String model, List<ChatMessage> messages, double temperature)
throws IOException, InterruptedException, LlmException {
int attempts = 0;
long waitMs = 1_000;
while (true) {
attempts++;
try {
return chat(model, messages, temperature);
} catch (LlmException e) {
boolean retryable = "rate-limited".equals(e.code());
if (!retryable || attempts >= 4) {
throw e;
}
Thread.sleep(waitMs); // 1s, then 2s, then 4s
waitMs *= 2;
}
}
}
/**
* Streams the reply token-by-token. Each decoded text fragment is handed to
* {@code onToken}; the call returns after the final "[DONE]" event.
*/
public void chatStream(String model, List<ChatMessage> messages,
Consumer<String> onToken)
throws IOException, InterruptedException, LlmException {
String body = json.writeValueAsString(Map.of(
"model", model,
"messages", messages,
"stream", true));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/chat/completions"))
.timeout(REQUEST_TIMEOUT)
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
.header("Accept", "text/event-stream")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<Stream<String>> response =
http.send(request, HttpResponse.BodyHandlers.ofLines());
if (response.statusCode() / 100 != 2) {
String errorBody;
try (Stream<String> lines = response.body()) {
errorBody = String.join("\n", lines.limit(50).toList());
}
throw toException(response.statusCode(), errorBody);
}
try (Stream<String> lines = response.body()) {
lines.forEach(line -> {
String data = line.trim();
if (!data.startsWith("data:")) {
return; // blank lines and comments
}
data = data.substring("data:".length()).trim();
if ("[DONE]".equals(data)) {
return;
}
String token = extractDelta(data);
if (token != null) {
onToken.accept(token);
}
});
}
}
/** Pulls choices[0].delta.content out of one SSE data payload; null if absent. */
private String extractDelta(String sseData) {
try {
JsonNode delta = json.readTree(sseData)
.path("choices").path(0).path("delta").path("content");
return (delta.isMissingNode() || delta.isNull()) ? null : delta.asText();
} catch (IOException e) {
return null; // malformed chunk: skip it rather than kill the stream
}
}
/** Maps HTTP status codes to typed, actionable failures. */
private LlmException toException(int status, String responseBody) {
return switch (status) {
case 400 -> new LlmException("bad-request", "400: " + responseBody);
case 401 -> new LlmException("auth",
"401 Unauthorized — the API key is missing or invalid. "
+ "Check OPENAI_API_KEY (the key itself is never logged).");
case 429 -> new LlmException("rate-limited",
"429 rate limited — back off and retry later.");
default -> new LlmException("http-" + status,
"HTTP " + status + ": " + responseBody);
};
}
}
Using it: the thread summarizer
A small driver wires the scenario together. Note the system message pins the output format, and the catch block handles each failure type separately — production code, not a demo with throws Exception.
package com.example.ai;
import java.io.IOException;
import java.util.List;
public final class ThreadSummarizer {
public static void main(String[] args) {
String thread = """
[2026-10-13 09:12] Customer: Checkout hangs after I click Pay.
[2026-10-13 09:40] Agent: Tried a different card?
[2026-10-13 10:05] Customer: Same with two cards. Orders page shows nothing.
[2026-10-13 11:20] Agent: Cleared cache, retried in incognito — still hangs.
""";
List<ChatMessage> messages = List.of(
new ChatMessage("system",
"You summarize customer support threads. Reply in under 120 words: "
+ "the problem, the steps already tried, and the current status."),
new ChatMessage("user", "Summarize this thread:\n\n" + thread));
LlmClient llm = new LlmClient();
try {
String summary = llm.chatWithRetry("gpt-4o-mini", messages, 0.3);
System.out.println(summary);
} catch (LlmException e) {
System.err.println("LLM call failed [" + e.code() + "]: " + e.getMessage());
} catch (IOException | InterruptedException e) {
System.err.println("Transport failure: " + e.getMessage());
Thread.currentThread().interrupt();
}
}
}
Problem: checkout hangs after clicking Pay; orders page shows nothing. Steps tried: a second card, cache clear, incognito retry — all still hang. Status: unresolved; the agent suspects a payment-gateway issue and is waiting on the payments team.
How it flows: request, response, and streaming
Why SSE streaming matters
With "stream": true, the server holds the connection open and sends Server-Sent Events: lines of the form data: {...}, each carrying the next token fragment in choices[0].delta.content, ending with data: [DONE]. HttpResponse.BodyHandlers.ofLines() gives you a Stream<String> over those lines — token-by-token output with no extra dependency.
Streaming doesn't make the model faster; it makes the perceived latency better. The first token can render in the UI while the rest is still generating. Two details from the client above are worth copying:
- Close the stream. It's a resource — the try-with-resources on the line stream closes the underlying connection.
- Read the error body before treating the stream as tokens. A 401 or 429 in streaming mode arrives as an HTTP error status with a short JSON body, not as SSE events. The client drains up to 50 lines of it for the exception message instead of trying to parse it as tokens.
Error handling: the rules of thumb
| Status | Meaning | What to do |
|---|---|---|
401 | Bad or missing key | Don't retry — fix the key. This is a config bug, not a transient failure. |
400 | Malformed request | Don't retry — log the request shape (never the key) and fix it. |
429 | Rate limited | Retry with exponential backoff (1s → 2s → 4s), then give up. Respect any Retry-After header the provider sends. |
5xx | Server trouble | Retry a few times with backoff, or once on an idempotent request. If it persists, it's not your code. |
| Timeout | Connect or request timeout fired | Treat as transient; retry if the call is safe to repeat (a read-only summary is). |
These are rules of thumb, not laws — providers publish their own limits, and docs change. The one rule that doesn't change: retry only what retrying can fix. A 401 retried four times is four wasted requests and a slower outage to diagnose.
When it breaks: four traps
1. The key leaks into the logs
The classic: someone logs the request headers for debugging, and the Authorization: Bearer sk-... line lands in the log aggregator, where everyone with log access can read it. Rule: the key is never printed, never logged, never concatenated into an error message. Note how toException above mentions the key's name but never its value.
2. No timeout anywhere
Default HttpClient has no request timeout. One slow provider and your request thread parks forever; under load, that's a thread-pool death spiral. Always set both connectTimeout (on the builder) and timeout (on the request).
3. Parsing without checking the error body
A 401 response has no choices array — it has {"error": {...}}. Code that skips the status check and goes straight to root.path("choices") throws a confusing NullPointerException (or a silent empty string) instead of the real diagnosis. Check the status first, then parse — and include the error body in the exception.
4. Blocking a request thread on streaming
chatStream holds a thread for the entire generation. That's fine in a desktop tool or a worker thread, but in a servlet container each streaming call pins a request thread for tens of seconds. At scale, move streaming to a dedicated executor or use the async HttpClient.sendAsync variant — don't let token streams eat your web tier's thread pool.
System.getenv("OPENAI_API_KEY") keeps the key out of source control, but environment variables can still leak through process listings, crash dumps, and CI logs. In production, prefer your platform's secret store (and rotate the key if you ever suspect exposure). Never commit a key to git — revoking and reissuing is the only fix.Try it
- Set
OPENAI_API_KEYin your shell (export OPENAI_API_KEY=...). - Add Jackson to your build (
com.fasterxml.jackson.core:jackson-databind). - Compile the three files (
ChatMessage,LlmException,LlmClient), plusThreadSummarizer. - Run the summarizer on one of your own support threads — then swap
chatWithRetryforchatStreamwithSystem.out::printas the consumer and watch the tokens arrive.
Next up in the track: prompt engineering from the developer's seat. Until then, the full series outline lives on the Java Learning Roadmap 2026 hub.
Comments
Post a Comment