Call a local LLM from Java with Ollama: HttpClient, a stateless request, then a chatbot with memory

Plain Java, no AI framework. We call Ollama's /api/chat with HttpClient and Jackson, prove the model remembers nothing between requests, then build a terminal chatbot that remembers, and see why the assistant role and the context window matter.

Three requests. Request 1 sends the user message This is Prasad, 5 tokens, and the model replies Nice to meet you, Prasad. Request 2 sends only What is my name?, 6 tokens, and the model replies Sorry, I don't know your name. Request 3 sends the earlier user message and assistant reply, highlighted as history, plus What is my name?, 20 tokens, and the model replies Your name is Prasad. A footer says the window starts empty every request, and the model doesn't remember, your app does.
Fig. 1 — The model starts every request with an empty window. In Java, the memory is just a List.

Most “AI in Java” tutorials start with a big framework. This one doesn’t. We use only what comes with Java (java.net.http.HttpClient) plus Jackson for JSON, so you can see exactly what goes over the wire to a local model. Once you understand this, frameworks like LangChain4j and Spring AI stop feeling like magic.

We build it up in steps, each a complete program:

  1. A stateless test: tell the model your name in one request, ask for it in the next. It won’t know. We’ll see exactly why.
  2. A chatbot with memory: a List<Message> that we send every time, explained line by line.
  3. The context window: why the list can’t grow forever.
  4. A tidier version: a system message, a clean way to quit, and history trimming.

This is part eight of a series, but it stands on its own. (Prefer Python? The same journey is in Call a local LLM from Python.)

Before you start

ollama pull qwen3.5:4b
  • Java 17 or newer. The code uses records, which need Java 16+, so any current LTS works.
  • Jackson for JSON. With Maven, add this to your pom.xml (any recent 2.x version works):
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.18.2</version>
</dependency>

Every program talks to one address: http://localhost:11434/api/chat, Ollama’s chat endpoint. The REST API guide explains every field of the JSON we send.

The JSON we are going to send

It helps to see the target first. This is the request body, exactly as you would paste it into Postman:

{
  "model": "qwen3.5:4b",
  "messages": [
    { "role": "user", "content": "Explain AI in two sentences." }
  ],
  "think": false,
  "stream": false
}

And the part of the response we care about:

{
  "message": { "role": "assistant", "content": "AI is a branch of computer science..." },
  "done": true
}

Our Java code builds the first JSON and digs message.content out of the second. That’s all.

Step 1: the model is stateless (it remembers nothing)

Here is a small program that makes two separate requests: first “This is Prasad”, then “What is my name?”.

package ai_simplest;

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;

public class StatelessDemo {

    public record Message(String role, String content) {}

    static final ObjectMapper JSON = new ObjectMapper();
    static final HttpClient HTTP = HttpClient.newHttpClient();

    public static void main(String[] args) throws Exception {
        // Request 1: introduce yourself
        String first = chat(List.of(new Message("user", "This is Prasad")));
        System.out.println("Request 1: " + first);

        // Request 2: a brand-new request with only the new question
        String second = chat(List.of(new Message("user", "What is my name?")));
        System.out.println("Request 2: " + second);
    }

    static String chat(List<Message> messages) throws Exception {
        Map<String, Object> body = Map.of(
                "model", "qwen3.5:4b",
                "messages", messages,
                "think", false,
                "stream", false);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:11434/api/chat"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)))
                .build();

        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        return JSON.readTree(response.body()).path("message").path("content").asText();
    }
}

Example output (the exact words will vary):

Request 1: Nice to meet you, Prasad! How can I help you today?
Request 2: I'm sorry, but I don't know your name. Could you tell me?

The model greeted Prasad by name, then a second later had no idea who you are. It didn’t forget. It never saw it. Request 2 contained only “What is my name?”, and that is all the model received.

That is what stateless means: every request starts with an empty context window. The model reads what is inside the current request, writes an answer, and keeps nothing. There are good reasons it is built this way:

  • The weights are frozen. Chatting doesn’t change the model; only training does. There is nowhere inside it to store your name. (See what a large language model is.)
  • One model, many users. The same model serves many conversations, so each request has to stand on its own.
  • It reads everything to predict. Each next token is chosen by looking at all the tokens in the window. What the model “knows” right now is exactly what’s in this request.
“The model doesn’t remember. Your app does.”

Step 2: a chatbot with memory

So the app has to remember. The idea is simple: keep every message in a List, and send the whole list on every request. Here is the complete chatbot from the video:

package ai_simplest;

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.*;

public class SimpleChatbot {

    public record Message (String role, String content) {}

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

        Scanner scanner = new Scanner(System.in);



        List<Message> history = new ArrayList<>();


        while(true) {

            Message message = new Message("user", scanner.nextLine());

            history.add(message);

            String body = getBody(history);

            String reply = chat(body);

            Message assistantMessage = new Message("assistant", reply);
            history.add(assistantMessage);

            System.out.println(reply);
        }



    }

    public static String getBody(List<Message> messages) throws Exception {
        Map<String, Object> body = new HashMap<>();
        body.put("model", "qwen3.5:4b");
        body.put("messages", messages);
        body.put("think", false);
        body.put("stream", false);

        return JSON.writeValueAsString(body);
    }

    public static String chat(String body) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:11434/api/chat"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();

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

        String reply = JSON.readTree(response.body()).path("message").path("content").asText();

        return reply;

    }

}

Run it, type a line, press Enter, and the model answers. Try it:

This is Prasad
Nice to meet you, Prasad! How can I help you today?
What is my name?
Your name is Prasad.

It remembers. The model didn’t change at all. Our List did the remembering. Stop the program with Ctrl+C.

Walking through the code

record Message(String role, String content): one chat message. A Java record gives us a tiny immutable class with a constructor and getters. Jackson turns it into exactly the JSON the API wants: {"role":"user","content":"..."}.

ObjectMapper JSON: Jackson’s converter between Java objects and JSON text. Created once and reused.

List<Message> history = new ArrayList<>(): this is the memory. It lives in your program, not in the model.

Then the loop does the same three things every turn:

  1. Add the question. scanner.nextLine() reads what you typed. We wrap it as new Message("user", ...) and add it to history.
  2. Send everything. getBody(history) builds the JSON for the whole list and chat(body) sends it.
  3. Remember the answer. The reply is wrapped as new Message("assistant", reply) and added to history, so it goes out with the next request.

getBody(...) puts four fields in a Map and serialises it:

  • "model": which model to run.
  • "messages": the whole history. Jackson serialises the List<Message> as a JSON array of objects.
  • "think": false: Qwen 3.5 reasons before answering by default; on a laptop that can take minutes. false skips it.
  • "stream": false: one complete JSON response instead of many small pieces, so we can read it in one go.

chat(...) sends it with Java’s built-in HTTP client:

  • HttpRequest.newBuilder() builds a POST to http://localhost:11434/api/chat with a Content-Type: application/json header and our JSON as the body.
  • send(..., BodyHandlers.ofString()) waits for the answer and gives us the body as a String.
  • JSON.readTree(...).path("message").path("content").asText() walks the response JSON down to message → content, the reply text. path(...) is forgiving: if a field is missing, you get an empty string instead of a NullPointerException.

What actually gets sent on turn 2

When you type “What is my name?”, the list holds three messages, and this is the body that goes to Ollama:

{
  "model": "qwen3.5:4b",
  "messages": [
    { "role": "user",      "content": "This is Prasad" },
    { "role": "assistant", "content": "Nice to meet you, Prasad!" },
    { "role": "user",      "content": "What is my name?" }
  ],
  "think": false,
  "stream": false
}

“Prasad” is now inside the request, so the model can answer. Turn 3 sends five messages, turn 4 sends seven, and so on.

Why we must add the assistant’s reply

You might ask: why send the model’s own answers back? Isn’t sending the user’s messages enough?

No. Without the assistant messages, the model sees only a list of questions with no answers:

user: This is Prasad
user: What is my name?
user: Explain that in simpler words.

It can’t tell what it said before, so follow-ups like “explain that more simply” or “give me another example” have nothing to point to, and it may repeat or contradict itself. Adding each reply with the role assistant gives the model both sides of the real conversation. (The roles are explained in depth in System, user and assistant roles explained.)

Step 3: the context window (why the list can’t grow forever)

Because we resend everything, every request is bigger than the last.

Six turns of a chat. Turn 1 sends 1 message, about 12 tokens. Turn 2 sends 3 messages, about 41 tokens. Turn 3 sends 5 messages, about 70 tokens, and so on up to turn 6 with 11 messages and about 171 tokens. Below, a context window bar fills up with system plus history plus new question, towards a dashed limit. A note says old turns eventually won't fit, so keep the system message and drop or summarise the oldest turns.
Each turn resends the whole conversation. Token counts are illustrative.

The context window is the maximum number of tokens the model can read in one request: the system message, the whole history and the new question together. Qwen 3.5 supports about 256K tokens. In practice:

  • Ollama may use a smaller window by default to save memory. You can raise it per request by adding "options", Map.of("num_ctx", 32768) to the body, or in the Ollama app’s settings. A bigger window uses more memory.
  • Bigger requests are slower, because the model reads the whole history on every turn.
  • Real apps fill the window fast. A shop’s support bot might send a system message (120 tokens), the full refund policy (about 6,000), the customer’s order (180) and the question (25): about 6,325 tokens for one message. Six messages later it has sent about 40,000 tokens, 36,000 of them the same policy again and again. Locally that costs time; on a cloud API it costs money per token.

The simplest fix is to keep only the most recent turns. Smarter fixes summarise old turns, or search your documents and send only the paragraph that matters (that is RAG).

Step 4: a tidier chatbot

SimpleChatbot is deliberately minimal, which is what makes it easy to learn from. Here is the same program with four small upgrades you’ll want in practice:

  • a system message at the top of the history, to set the rules,
  • /bye to quit cleanly (and no crash when input ends),
  • one shared HttpClient instead of a new one per request,
  • history trimming, to respect the context window, plus a clear error if Ollama returns one.
package ai_simplest;

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.*;

public class TutorChatbot {

    public record Message(String role, String content) {}

    static final ObjectMapper JSON = new ObjectMapper();
    static final HttpClient HTTP = HttpClient.newHttpClient();   // create once, reuse
    static final int MAX_TURNS = 10;                             // user + assistant pairs to keep

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        List<Message> history = new ArrayList<>();
        history.add(new Message("system", "You are a friendly Java tutor. Keep answers short."));

        System.out.println("Chat with qwen3.5:4b (type /bye to quit)");
        while (scanner.hasNextLine()) {
            System.out.print("You: ");
            String text = scanner.nextLine().trim();
            if (text.equals("/bye")) break;
            if (text.isEmpty()) continue;

            history.add(new Message("user", text));
            String reply = chat(history);
            history.add(new Message("assistant", reply));
            trim(history);

            System.out.println("AI: " + reply + "\n");
        }
    }

    // Keep the system message plus the last MAX_TURNS exchanges.
    static void trim(List<Message> history) {
        int keep = 1 + MAX_TURNS * 2;
        while (history.size() > keep) {
            history.remove(1);   // index 0 is the system message
        }
    }

    static String chat(List<Message> messages) throws Exception {
        Map<String, Object> body = Map.of(
                "model", "qwen3.5:4b",
                "messages", messages,
                "think", false,
                "stream", false);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:11434/api/chat"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)))
                .build();

        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 200) {
            throw new IllegalStateException("Ollama returned " + response.statusCode() + ": " + response.body());
        }
        return JSON.readTree(response.body()).path("message").path("content").asText();
    }
}

A few notes:

  • The system message is index 0 and is never trimmed, so the bot keeps its rules even in a long chat. trim removes the oldest user and assistant messages from index 1 onward.
  • scanner.hasNextLine() ends the loop cleanly when input runs out, instead of throwing NoSuchElementException.
  • HttpClient is designed to be created once and reused; it keeps connections open between requests.
  • Checking statusCode() turns “model not found” or a bad request into a clear message instead of an empty reply.

Want the words to appear as they’re written?

Set "stream" to true and Ollama sends many small JSON lines instead of one. With HttpClient you can read them with BodyHandlers.ofLines(), parse each line with Jackson, print message.content as it arrives, and stop when done is true. Remember to join the pieces and still add the full reply to history as an assistant message. The REST API guide shows what the stream looks like.

Troubleshooting

  • java.net.ConnectException: Ollama isn’t running. Open the Ollama app, or run ollama serve.
  • An empty reply, or status 404: the model isn’t downloaded or the name doesn’t match. Run ollama pull qwen3.5:4b and check ollama list.
  • Very slow answers: make sure "think" is false, try a smaller model, and remember the first request also loads the model into memory.
  • NoSuchElementException from Scanner: input ended (for example you piped a file in). The tidier version above handles it with hasNextLine().

Key takeaways

  • You can call a local LLM from plain Java: a POST with HttpClient to http://localhost:11434/api/chat, JSON built and read with Jackson.
  • The model is stateless: each request starts with an empty window, and nothing is kept afterwards.
  • The chatbot’s memory is just a List<Message>: add the user message, send the whole list, add the assistant reply.
  • Always add the reply with the role assistant, or follow-ups lose their meaning.
  • History grows every turn. Respect the context window: keep the system message, trim old turns, and send only what’s needed.

The full series: Run LLMs locally with Ollama

Each part stands on its own, so jump to whichever you need:

  1. How to run an LLM on your own computer
  2. What is Ollama? The video player for AI models, and localhost:11434 explained
  3. Ollama CLI commands: the complete cheat sheet
  4. The Ollama desktop app: chat, pick models, and launch Claude Code or Copilot
  5. System, user and assistant roles explained
  6. Ollama REST API: /api/generate vs /api/chat
  7. Call a local LLM from Python: a stateless request, then a chatbot with memory
  8. Call a local LLM from Java: HttpClient, a stateless request, then a chatbot with memory (you are here)

See it in action

Prefer watching? This video walks through the same ideas with live, hands-on demos.

Video thumbnail: Call a local LLM from Java with Ollama: HttpClient, a stateless request, then a chatbot with memoryWatch on YouTube ↗

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.