Clavem

How to validate a license key in a Java app

POST the key and the saved instance id to /v1/licenses/validate with the JDK's HttpClient, which returns every HTTP status as a normal response, read the body with Jackson, and map the answer to a record. Keep the key in the system keyring, and run the call off the UI thread.

This page covers the online validate call in Java. The token check for the offline path is in offline verification in Java, and the first-run call is in device activation in Java. The Java code in this guide was not compiled or run, because the JDK available for testing was Java 8 and the code needs Java 17. It uses documented APIs, and the server behavior it relies on was checked against the live API.

The client

Java 11 added java.net.http.HttpClient, which needs no dependency. It returns a response for every HTTP status, so a 404 or 429 is not an exception. Only a network failure or a timeout throws. Jackson is the usual JSON library:

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.HashMap;
import java.util.Map;

public final class LicenseClient {
    public enum Kind { VALID, NOT_VALID, UNKNOWN, NO_ANSWER }

    public record Outcome(Kind kind, String token, String reason, Duration retryAfter) {}

    private final URI base;
    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    private final ObjectMapper json = new ObjectMapper();

    public LicenseClient(URI base) { this.base = base; }

    public LicenseClient() { this(URI.create("https://clavem.io")); }

    public Outcome validate(String key, String instanceId) {
        Map<String, String> body = new HashMap<>();
        body.put("license_key", key);
        if (instanceId != null) body.put("instance_id", instanceId);

        try {
            HttpRequest request = HttpRequest.newBuilder(base.resolve("/v1/licenses/validate"))
                .timeout(Duration.ofSeconds(8))
                .header("Content-Type", "application/json")
                .header("User-Agent", "Inkwell/3.2")
                .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)))
                .build();
            HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());

            JsonNode reply = parse(response.body());
            String message = reply.path("error").textValue();       // null for a JSON null: no exception
            switch (response.statusCode()) {
                case 200:
                    if (!reply.path("valid").isBoolean()) return noAnswer(null);
                    String token = reply.path("token").textValue();
                    return reply.path("valid").asBoolean()
                        ? new Outcome(Kind.VALID, token, null, null)
                        : new Outcome(Kind.NOT_VALID, token, message, null);
                case 404:
                    return new Outcome(Kind.UNKNOWN, null, message, null);
                case 429:
                case 503:
                    return noAnswer(retryAfter(response));
                default:
                    return noAnswer(null);                          // 400 is a bug in the app; other 5xx is on the server
            }
        } catch (IOException e) {
            return noAnswer(null);                                  // offline, DNS failure, timeout
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return noAnswer(null);
        }
    }

    private JsonNode parse(String body) {
        try { return json.readTree(body); } catch (IOException e) { return json.createObjectNode(); }
    }

    private static Duration retryAfter(HttpResponse<?> response) {
        return response.headers().firstValue("Retry-After").map(v -> {
            try { return Duration.ofSeconds(Long.parseLong(v.trim())); } catch (NumberFormatException e) { return null; }
        }).orElse(null);
    }

    private static Outcome noAnswer(Duration retryAfter) { return new Outcome(Kind.NO_ANSWER, null, null, retryAfter); }
}

HttpTimeoutException is a subclass of IOException, so the catch covers timeouts too. textValue() returns null for a JSON null, which suits this API: a successful reply has "error": null. Reading it with asText() would return the four-letter string "null".

What each answer means

Reply Kind What the app does
200, valid: true VALID Store the new token. This restarts the 14-day window.
200, valid: false NOT_VALID Expired or disabled. Store the token, show the reason, keep the key.
404 UNKNOWN Unknown key, or instance_id not found. Clear the license, ask for the key.
429 (Retry-After: 60), 503 (Retry-After: 5) NO_ANSWER No verdict. Use the stored token and retry later.
IOException NO_ANSWER Offline or timeout. Same.

Retry a 503 once for its 5 seconds, with Thread.sleep on a worker thread, and never hold a launch for the 60 seconds of a 429. An empty body returns {"valid":false,"error":"license_key: Invalid input: expected string, received undefined"} with a 400 from the live API. That is a bug in your call, not a customer problem.

Keep the key off the UI thread and out of plain text

Run the check on a background thread and update the UI when it finishes. With Swing, SwingWorker. With JavaFX, a Task. Or use sendAsync and compose with CompletableFuture. Never call send on the event thread.

For storage, Java has no standard secret store. java.util.prefs.Preferences writes the registry, a property list or an XML file, all readable by the user, so it is not one. The java-keyring library wraps the Keychain, Credential Manager and the Secret Service behind one small interface:

import com.github.javakeyring.Keyring;
import com.github.javakeyring.PasswordAccessException;

Keyring keyring = Keyring.create();                       // throws BackendNotSupportedException without a backend
keyring.setPassword("com.example.inkwell", "license", jsonOfSaved);
String stored = keyring.getPassword("com.example.inkwell", "license");   // throws PasswordAccessException when missing
keyring.deletePassword("com.example.inkwell", "license");

Treat PasswordAccessException as “no license saved”, and BackendNotSupportedException as “no secure store here”. On a Linux server there usually is none. Decide whether that blocks the app or falls back to a file with owner-only permissions, using Files.setPosixFilePermissions.

Pitfalls specific to Java

  • send blocks. On the Swing or JavaFX thread it freezes the window. Use a worker or sendAsync.
  • Corporate proxies. The JDK client uses ProxySelector.getDefault(). To follow the system proxy settings, start the JVM with -Djava.net.useSystemProxies=true or set a selector yourself.
  • Corporate CAs. The JDK checks certificates against its own cacerts store, not always the operating system’s. A customer behind a TLS-inspecting proxy needs the proxy’s CA in the store your runtime uses.
  • InterruptedException. Restore the interrupt flag, as above, or shutdown logic elsewhere misbehaves.
  • Share one HttpClient. It owns a connection pool and its threads.

Doing this with Clavem

The License API needs no secret, so nothing sensitive ships in the JAR. Plan limits never block validation. See the API reference for every field.

Questions

Does java.net.http.HttpClient throw on a 404?

No. send returns an HttpResponse for any status code. It throws IOException for network failures, HttpTimeoutException for a timeout, and InterruptedException if the thread is interrupted. Read statusCode and the headers yourself.

Where should a Java desktop app store a license key?

In the operating system's credential store, through a library such as java-keyring, or DPAPI through JNA on Windows. Preferences and properties files are plain text, readable and editable by the user.

Can I call the license check from the Swing event thread?

Not safely. Even an 8-second timeout freezes the window. Use sendAsync or a SwingWorker, or the JavaFX Task class, and update the UI when the CompletableFuture completes.

Sources

  1. Java SE 17, java.net.http.HttpClient (checked November 2026)