Every Java AI framework, whether Spring AI, LangChain4j or an official SDK, does the same thing underneath: it sends an HTTP POST with some JSON and reads JSON back. Once you have done that yourself, the frameworks stop feeling like magic. You will also know exactly where to look when something breaks.
So in this part of Java for AI Engineers, we call an LLM with nothing but the JDK and Jackson. We build it up in four steps, each a complete program you can run:
- A first call: the raw JSON in and out, no libraries at all.
- Records instead of strings: send and read the JSON as Java types.
- A small client you could actually use: settings from environment variables, timeouts, error handling and retries.
- Streaming: print the answer word by word as it is written.
This is the written companion to episode 3 of the YouTube series, “Talking to an LLM with code”. The episode’s own code is in the ep3-talking-to-llm repo.
Before you start
- Java 17 or newer (records need 16+). Everything here also runs on Java 21 and 25.
- A model to talk to. The easiest is Ollama on your own computer: free, private and no API key. We use the
qwen3.5:4bmodel:
ollama pull qwen3.5:4b
Prefer a cloud model? Any provider with an OpenAI-compatible API works. You only change three settings (step 3).
- Jackson for JSON, from Step 2 on. With Maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
Java has no JSON library in the JDK yet. A built-in one is being worked on in OpenJDK, but for now Jackson is the usual choice.
The format we use, and why
There is no single standard LLM API, but one format comes close: OpenAI’s Chat Completions format. You POST to an address ending in /chat/completions with a JSON body like this:
{
"model": "qwen3.5:4b",
"messages": [
{ "role": "system", "content": "You are a friendly teacher. Keep answers short." },
{ "role": "user", "content": "Explain AI in two sentences." }
],
"temperature": 0.2
}
And the answer comes back like this (trimmed):
{
"choices": [
{
"message": { "role": "assistant", "content": "AI is software that learns patterns..." },
"finish_reason": "stop"
}
],
"usage": { "prompt_tokens": 24, "completion_tokens": 31, "total_tokens": 55 }
}
OpenAI’s own API uses it, and so do Ollama (at http://localhost:11434/v1), local servers like vLLM and LM Studio, and many cloud providers. Learn it once and you can talk to all of them.
Two honest notes. First, OpenAI now recommends its newer Responses API for new projects on OpenAI’s own platform, while Chat Completions stays supported. Second, some providers, like Anthropic, have their own native format as well. The ideas are the same everywhere: a list of messages goes in, a message comes out. The fields temperature, usage and finish_reason are explained in part 2.
Step 1: the first call, with no libraries
This program uses only the JDK. The JSON is a text block, so it looks exactly like what goes over the wire.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class FirstCall {
public static void main(String[] args) throws Exception {
String json = """
{
"model": "qwen3.5:4b",
"messages": [
{ "role": "user", "content": "Explain AI in two sentences." }
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:11434/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer ollama")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}
Run it and you get 200 and the full JSON reply. (The words will be different every time; part 2 explains why.)
Line by line:
HttpRequest.newBuilder()builds a normal HTTP POST. Nothing about it is special to AI.Authorization: Bearer ...is how OpenAI-style APIs receive your API key. Ollama doesn’t check it, but sending it means the same code works with a cloud provider later.client.send(...)blocks until the whole answer has been written. For a long answer that can take several seconds.
This works, but building JSON by hand gets messy fast, and we still have to dig the answer out of the reply. Time for Jackson.
Step 2: records instead of strings
We describe the request and the response as records, and let Jackson convert them to and from JSON.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
public class TypedCall {
// What we send
record Message(String role, String content) {}
record ChatRequest(String model, List<Message> messages, double temperature) {}
// What we read back (only the fields we need)
@JsonIgnoreProperties(ignoreUnknown = true)
record ChatResponse(List<Choice> choices, Usage usage) {}
@JsonIgnoreProperties(ignoreUnknown = true)
record Choice(Message message, String finish_reason) {}
@JsonIgnoreProperties(ignoreUnknown = true)
record Usage(int prompt_tokens, int completion_tokens, int total_tokens) {}
static final ObjectMapper JSON = new ObjectMapper();
static final HttpClient HTTP = HttpClient.newHttpClient();
public static void main(String[] args) throws Exception {
ChatRequest chat = new ChatRequest(
"qwen3.5:4b",
List.of(
new Message("system", "You are a friendly teacher. Keep answers short."),
new Message("user", "Explain AI in two sentences.")),
0.2);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:11434/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer ollama")
.POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(chat)))
.build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
ChatResponse result = JSON.readValue(response.body(), ChatResponse.class);
Choice first = result.choices().get(0);
System.out.println(first.message().content());
System.out.println("Stopped because: " + first.finish_reason());
System.out.println("Tokens in: " + result.usage().prompt_tokens()
+ ", out: " + result.usage().completion_tokens());
}
}
Example output (your words will differ):
AI is software that learns patterns from examples. An LLM is AI that predicts the next piece of text.
Stopped because: stop
Tokens in: 24, out: 31
What changed:
- The JSON is now Java types.
ChatRequestturns into exactly the JSON from the top of this page. The field names of the records become the JSON keys, which is why some of them usesnake_case, likefinish_reason. That is the API’s naming, not Java’s. @JsonIgnoreProperties(ignoreUnknown = true)tells Jackson to skip fields we didn’t declare. The real response has many more fields (id,created,model…), and providers add new ones over time. Without this, a new field would break your code.- We read
finish_reasonandusage. In real apps, log both.usageis what you pay for, andfinish_reasonof"length"means the answer was cut off.
Step 3: a small client you could actually use
The first two programs are fine for learning, but they would hurt in production: the address and model are hard-coded, nothing stops a request from hanging forever, and any error just turns into a confusing parse failure. Let’s fix all three in one small class.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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;
public class LlmClient {
record Message(String role, String content) {}
record ChatRequest(String model, List<Message> messages, double temperature) {}
@JsonIgnoreProperties(ignoreUnknown = true)
record ChatResponse(List<Choice> choices) {}
@JsonIgnoreProperties(ignoreUnknown = true)
record Choice(Message message) {}
private static final ObjectMapper JSON = new ObjectMapper();
private final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
private final String baseUrl;
private final String apiKey;
private final String model;
LlmClient(String baseUrl, String apiKey, String model) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.model = model;
}
/** Reads the settings from environment variables, with local Ollama as the default. */
static LlmClient fromEnv() {
return new LlmClient(
env("LLM_BASE_URL", "http://localhost:11434/v1"),
env("LLM_API_KEY", "ollama"),
env("LLM_MODEL", "qwen3.5:4b"));
}
String chat(List<Message> messages) throws IOException, InterruptedException {
String body = JSON.writeValueAsString(new ChatRequest(model, messages, 0.2));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/chat/completions"))
.timeout(Duration.ofSeconds(60))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
int maxAttempts = 3;
for (int attempt = 1; ; attempt++) {
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status == 200) {
ChatResponse result = JSON.readValue(response.body(), ChatResponse.class);
return result.choices().get(0).message().content();
}
boolean worthRetrying = status == 429 || status >= 500;
if (!worthRetrying || attempt == maxAttempts) {
throw new IOException("LLM call failed with HTTP " + status + ": " + response.body());
}
long waitMs = 1000L * attempt; // 1s, then 2s
System.err.println("HTTP " + status + ", retrying in " + waitMs + " ms");
Thread.sleep(waitMs);
}
}
private static String env(String name, String fallback) {
String value = System.getenv(name);
return value == null || value.isBlank() ? fallback : value;
}
public static void main(String[] args) throws Exception {
LlmClient llm = LlmClient.fromEnv();
String answer = llm.chat(List.of(
new Message("system", "You are a friendly teacher. Keep answers short."),
new Message("user", args.length > 0 ? args[0] : "Explain AI in two sentences.")));
System.out.println(answer);
}
}
The three fixes:
1. Settings come from the environment. The base URL, API key and model are read from environment variables, with local Ollama as the default. Never put an API key in your code or in Git. To switch provider, you change settings, not code:
| Provider | LLM_BASE_URL |
LLM_API_KEY |
LLM_MODEL |
|---|---|---|---|
| Ollama on your laptop | http://localhost:11434/v1 |
anything (ignored) | qwen3.5:4b |
| OpenAI | https://api.openai.com/v1 |
your OpenAI key | a model name from OpenAI’s docs |
| Another compatible provider | the base URL from its docs | your key for it | a model name from its docs |
2. Timeouts. connectTimeout stops us waiting forever for a server that isn’t there. The per-request timeout puts an upper limit on the whole call. LLM calls are slow compared to normal APIs, so the limit is generous (60 seconds), but it is there.
3. Errors are errors. We check the status code before parsing. Only two kinds of failure are worth trying again:
- 429 Too Many Requests: you hit the provider’s rate limit. Waiting a little usually fixes it.
- 5xx: a problem on the server side, often temporary.
Everything else, like 401 (bad key), 404 (wrong URL or unknown model) or 400 (bad request), will fail the same way every time, so we stop right away and include the response body. That body almost always says exactly what is wrong. We wait a bit longer before each retry (1 second, then 2), and give up after three attempts.
Step 4: streaming the answer as it is written
The model writes one token at a time, but send waits for all of them. For a chat app, it feels much faster to show the words as they arrive. Add "stream": true, and the server sends small pieces as server-sent events: lines that start with data: , each holding a bit of JSON, ending with data: [DONE].
HttpClient can hand us the response line by line with BodyHandlers.ofLines():
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
public class StreamingCall {
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
Map<String, Object> body = Map.of(
"model", "qwen3.5:4b",
"stream", true,
"messages", List.of(Map.of("role", "user", "content", "Say something about Java.")));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:11434/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer ollama")
.POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)))
.build();
HttpResponse<Stream<String>> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofLines());
try (Stream<String> lines = response.body()) {
lines.filter(line -> line.startsWith("data: "))
.map(line -> line.substring("data: ".length()))
.takeWhile(data -> !data.equals("[DONE]"))
.forEach(data -> {
try {
JsonNode delta = JSON.readTree(data).path("choices").path(0).path("delta");
System.out.print(delta.path("content").asText(""));
System.out.flush();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
System.out.println();
}
}
Each event carries a delta, the new piece of text, instead of a full message. We print each piece as it arrives and stop at [DONE]. Empty lines between events are skipped by the filter. (Here we used a Map for the request body to keep the example short. In a real app, add a stream field to your request record.)
When things go wrong
| What you see | What it usually means |
|---|---|
ConnectException |
Nothing is listening at that address. Is Ollama running? Is the URL right? |
| HTTP 401 | Missing or wrong API key. Check LLM_API_KEY. |
| HTTP 404 | Wrong path (did you forget /v1?) or a model name the server doesn’t know. With Ollama, run ollama pull first. |
| HTTP 400 | The JSON has a field the model doesn’t accept. Some models, for example, refuse a custom temperature. Read the response body. |
| HTTP 429 | Rate limit. Retry after a short wait, and don’t send too many requests at once. |
Jackson UnrecognizedPropertyException |
You forgot @JsonIgnoreProperties(ignoreUnknown = true) on a response record. |
| The answer stops mid-sentence | finish_reason is "length": the answer hit the length limit. |
So when do I need a framework?
For one call, you don’t. Fifty lines of plain Java is honest, easy to debug and has no extra dependencies.
A framework like Spring AI or LangChain4j starts to pay off when you need many of these at once: chat memory, tools the model can call, structured output into your own types, RAG over your documents, several providers, and metrics. They do all of that on top of the same HTTP call you just wrote. We get to both later in this series.
If you want to see conversation memory built by hand in the same plain-Java style, read Call a local LLM from Java with Ollama. It proves the model is stateless and builds a chatbot that remembers, using a List<Message>.
Key takeaways
- Calling an LLM is an HTTP POST with JSON.
HttpClientfrom the JDK is enough. - The Chat Completions format works with OpenAI, Ollama and many other providers. Learn it once.
- Use records for the request and response, and
@JsonIgnoreProperties(ignoreUnknown = true)on response records. - Keep the base URL, API key and model in configuration. Never commit a key.
- Always set timeouts, check the status code, and retry only on 429 and 5xx, with a growing wait.
- For chat apps, stream the answer with
"stream": trueandBodyHandlers.ofLines().
Frequently asked questions
How do I call the OpenAI API from Java without a library?
Use java.net.http.HttpClient to send a POST to https://api.openai.com/v1/chat/completions, with your key in an Authorization: Bearer header and a JSON body holding the model and messages. Parse the reply with Jackson. Step 3 above is a complete example.
Can the same Java code call Ollama and OpenAI?
Yes. Ollama offers an OpenAI-compatible API at http://localhost:11434/v1. Change the base URL, API key and model name, and the same code works with both.
Do I need Spring AI or LangChain4j to use an LLM in Java?
No. They are helpful when your app needs memory, tools, RAG or several providers, but a single LLM call needs nothing beyond the JDK and a JSON library.
Why does my LLM call take so long?
The model writes the answer one token at a time, and send waits for the last one. Long answers take longer. Ask for shorter answers, set a token limit, or stream the response so users see words right away.
How should I store my API key in Java?
Read it from an environment variable or your app’s secret store, never from source code. In Spring Boot, put it in configuration backed by an environment variable or a secrets manager.
Next in the series
Previous: How LLMs work: tokens, context windows and temperature. Next: Java 21 features for AI apps, where records, sealed types, pattern matching and virtual threads turn this client into clean, safe and fast application code.
Comments