# Add e-signatures and clickwrap to Java

> Add e-signatures and clickwrap to plain Java with the JDK's HttpClient and HttpServer: POST /v1/sessions, GET /v1/records, a signed cookie and Gson.

Source: https://esigncomply.com/java

Stack · Java

To add e-signatures and clickwrap to Java, call the REST API with the JDK's `HttpClient`: there is no package, because the server SDK exists for Node.js only. One class with no framework creates the session with the secret key, keeps the pinned versions in a signed cookie, and confirms the record. Esign Comply seals each acceptance as an independent record.

Follow the quickstart and each signature is a valid electronic signature under the U.S. ESIGN Act, state UETA laws and New York's ESRA, and each clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/java)

No artifact for the API: the JDK's HttpClient is enough. Gson is the one jar, for the JSON

[Java quickstart](https://esigncomply.com/docs/quickstart/java)

Free plan: 10 live signatures a month and a full test mode. No card required.

Last updated November 26, 2026

Run in Java before publishing

**The API call**

App.java (excerpt)

```java
/** One call to the Esign Comply API. Returns the status and the JSON, read into the record you name. */
static <T> Answer<T> esc(String method, String path, Object body, String idempotencyKey, Class<T> type) throws IOException, InterruptedException {
    // Without timeout() a request waits for its answer forever.
    HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(API + path))
        .timeout(Duration.ofSeconds(10))
        .header("Authorization", "Bearer " + API_KEY)
        .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(JSON.toJson(body)));
    if (body != null) request.header("Content-Type", "application/json");
    if (idempotencyKey != null) request.header("Idempotency-Key", idempotencyKey);
    for (int attempt = 1; ; attempt++) {
        // The client does not throw on 4xx and 5xx: the status is here, and the error envelope is the body.
        HttpResponse<String> response = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 429 || attempt == 3) {
            return new Answer<>(response.statusCode(), JSON.fromJson(response.body(), type));
        }
        // Over the rate limit: wait for Retry-After (1 to 5 seconds) and try again, twice at most. Nothing else is retried.
        long seconds = response.headers().firstValue("Retry-After").filter(value -> value.matches("\\d{1,4}")).map(Long::parseLong).orElse(1L);
        Thread.sleep(Duration.ofSeconds(Math.clamp(seconds, 1, 5)));
    }
}
```

**Create the session**

App.java (excerpt)

```java
// Step 4: create the session with the secret key. The browser gets the client token only.
static void ceremony(HttpExchange exchange) throws Exception {
    // The page that runs the ceremony: the origin the browser reports, or the Host header of the request.
    String origin = exchange.getRequestHeaders().getFirst("Origin");
    if (origin == null) origin = "http://" + exchange.getRequestHeaders().getFirst("Host");
    Answer<Session> created = esc("POST", "/sessions", Map.of(
        "profile", PROFILE,
        "signer", SIGNER,
        "documents", List.of(
            Map.of("document", DOCUMENTS.get("terms"), "version", "current"),
            Map.of("document", DOCUMENTS.get("privacy"), "version", "current")),
        "context", Map.of("url", origin + "/signup", "locale", "en-US", "purpose", "account_signup")),
        "signup-" + SIGNER.get("external_id") + "-" + UUID.randomUUID(), Session.class);
    Session session = created.body();
    if (created.status() != 201) {
        json(exchange, 502, Map.of("error", session.error() == null ? "unknown" : session.error().code()));
        return;
    }

    List<String> versionIds = session.documents().stream().map(Doc::versionId).sorted().toList();
    exchange.getResponseHeaders().add("Set-Cookie", pinnedCookie(new Pinned(SIGNER.get("external_id"), versionIds)));
    json(exchange, 200, Map.of("clientToken", session.clientToken(), "apiUrl", session.apiUrl(), "documents", session.documents()));
}
```

**Confirm**

App.java (excerpt)

```java
// Step 6: confirm the record with the secret key before the account exists.
static void confirm(HttpExchange exchange) throws Exception {
    String recordId = "missing";
    try {
        Object body = JSON.fromJson(new String(exchange.getRequestBody().readAllBytes(), UTF_8), Map.class);
        if (body instanceof Map<?, ?> map && map.get("recordId") instanceof String id) recordId = id;
    } catch (JsonSyntaxException malformed) {
        // an empty or malformed body is refused below
    }
    Pinned expected = pinned(exchange);
    Answer<Signed> answer = esc("GET", "/records/" + URLEncoder.encode(recordId, UTF_8), null, null, Signed.class);
    Signed record = answer.body();

    boolean confirmed = answer.status() == 200
        && record.status() != null && SEALED.contains(record.status())
        && Boolean.valueOf(LIVE).equals(record.livemode())
        && expected.signerId() != null && record.signer() != null && expected.signerId().equals(record.signer().externalId())
        && record.documents().stream().map(Doc::versionId).sorted().toList().equals(expected.versionIds());

    System.out.println(confirmed ? "confirmed " + record.id() + " (" + record.status() + ")" : "refused");
    if (!confirmed) {
        json(exchange, 409, Map.of("confirmed", false));
        return;
    }
    // Only now create the account, and store record.id() and the receipt with it.
    json(exchange, 200, Map.of("confirmed", true, "recordId", record.id()));
}
```

**Signed cookie**

App.java (excerpt)

```java
// Server-owned state: there is no session, so it is a cookie this class signs with HMAC-SHA256.
// The visitor can read it and cannot change it.
static String sign(String payload) throws GeneralSecurityException {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(COOKIE_SECRET, "HmacSHA256"));
    return HexFormat.of().formatHex(mac.doFinal(payload.getBytes(UTF_8)));
}

static String pinnedCookie(Pinned pinned) throws GeneralSecurityException {
    String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.toJson(pinned).getBytes(UTF_8));
    return "esc_signup=" + payload + "." + sign(payload) + "; Path=/; HttpOnly; SameSite=Lax" + (LIVE ? "; Secure" : "");
}

static Pinned pinned(HttpExchange exchange) throws GeneralSecurityException {
    for (String header : exchange.getRequestHeaders().getOrDefault("Cookie", List.of())) {
        Matcher cookie = Pattern.compile("(?:^|; ?)esc_signup=([\\w-]+)\\.([0-9a-f]+)").matcher(header);
        // MessageDigest.isEqual compares in constant time. A cookie that fails is the same as no cookie.
        if (cookie.find() && MessageDigest.isEqual(sign(cookie.group(1)).getBytes(UTF_8), cookie.group(2).getBytes(UTF_8))) {
            return JSON.fromJson(new String(Base64.getUrlDecoder().decode(cookie.group(1)), UTF_8), Pinned.class);
        }
    }
    return new Pinned(null, List.of());
}
```

Integrate with Java

## How do you integrate Esign Comply with Java?

In plain Java the integration is one `App.java`: the JDK's `HttpServer` with an executor answers four addresses, and `java.net.http.HttpClient` makes the calls. Gson reads the answers into records, and the pinned versions travel in a cookie signed with `javax.crypto.Mac`, because plain Java has no session. The JDK's source launcher runs the file with no build.

The JDK documentation says of com.sun.net.httpserver.HttpServer: This class implements a simple HTTP server.

Source: [JDK 25 API, HttpServer](https://docs.oracle.com/en/java/javase/25/docs/api/jdk.httpserver/com/sun/net/httpserver/HttpServer.html), read on November 26, 2026.

[Java quickstart](https://esigncomply.com/docs/quickstart/java) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in Java

- **The API call** · `App.java`
- **Create the session** · `App.java`
- **Confirm** · `App.java`
- **Signed cookie** · `App.java`

Run on 2026-11-26 with Java 25.0.5.1 (Eclipse Temurin, in the official Maven container image, with the JDK alone and no Maven build), the JDK's own HttpClient pinned to HTTP/1.1 and its com.sun.net.httpserver.HttpServer, and Gson 2.15.0 as the only jar, no framework, under the source launcher (java App.java) and from classes compiled with javac, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode over plain http. Its calls over https were not run.

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a Java app?

Paste this into Cursor, Claude Code or the AI coding tool that is open on your project. It names the packages that exist, where the secret key goes in Java, what to build and what never to do, and it ends with the rules block for your project.

The rules block lives at [/rules.md](https://esigncomply.com/rules.md). Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version, with your own document and profile IDs.

[Pages for each AI tool](https://esigncomply.com/build)

Prompt: Esign Comply clickwrap in Java

```java
Add Esign Comply clickwrap to my Java app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/java.md (the steps and the tested code for Java)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Java facts
- There is no Esign Comply package for Java. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with java.net.http.HttpClient, Authorization: Bearer and the secret key.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Java does not read .env files. System.getenv returns null for a missing variable: stop at start with a message. Never print the key.
- HttpClient: set timeout() on every request (without it a request waits forever) and connectTimeout() on the client. It does not throw on 4xx and 5xx: read statusCode() and the error envelope. Pin HttpClient.Version.HTTP_1_1 unless the project already relies on HTTP/2: by default the client asks a plain-http server to upgrade to HTTP/2.
- The JDK has no JSON parser. Use the JSON library the project already has, or Gson. Never parse JSON with string functions. Read the API's snake_case fields into records, and declare livemode as Boolean, not boolean: a missing boolean is read as false.
- With com.sun.net.httpserver.HttpServer, call setExecutor: the default handles every request on one thread. Catch exceptions in the handler and answer 500: an exception that leaves the handler closes the connection with no answer.
- There is no session. Keep the signer ID and the pinned version IDs in a cookie signed with javax.crypto.Mac (HmacSHA256) and compare the signature with MessageDigest.isEqual. The visitor can read a signed cookie: put nothing secret in it.
- The JDK has no function that escapes HTML. Print the document HTML as it is, and check everything else you print.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the signed cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the signed cookie. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:8000/signup --callback http://localhost:8000/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

3 things to watch

## What goes wrong when you add e-signatures in Java?

These are specific to Java. Each one was seen while the quickstart's code was run, or is in Java's own documentation.

- **The JDK HttpClient asks a plain-http server to upgrade to HTTP/2**

  The JDK documentation says a new client prefers HTTP/2 and that each request will attempt to upgrade. In the test on Java 25.0.5.1 the request carried `Upgrade: h2c`. A server that ignored it answered in HTTP/1.1. The test API, over plain http, closed the connection, and `send` threw `IOException: HTTP/1.1 header parser received no bytes`. The quickstart pins `HttpClient.Version.HTTP_1_1`. Its calls over https were not run.

  Source: [JDK 25 API, HttpClient.Builder](https://docs.oracle.com/en/java/javase/25/docs/api/java.net.http/java/net/http/HttpClient.Builder.html), read on November 26, 2026.

- **HttpServer handles every request on one thread until you set an executor**

  The JDK documentation says that without an executor a default is used, which uses the thread created by `start()`. In the test without `setExecutor`, page requests sent while four confirmations were in flight waited up to 1.2 seconds behind a call that was waiting to retry. With `Executors.newVirtualThreadPerTaskExecutor()` they were answered in under 0.01 seconds.

  Source: [JDK 25 API, HttpServer](https://docs.oracle.com/en/java/javase/25/docs/api/jdk.httpserver/com/sun/net/httpserver/HttpServer.html), read on November 26, 2026.

- **A boolean record field reads a missing livemode as false**

  In the test with Gson 2.15.0, an error envelope read into a record with `boolean livemode` gave `false`, which is the value a test deployment expects. With `Boolean livemode` it gave `null`, and the check fails. The quickstart declares every field it reads as an object and compares with `Boolean.valueOf(LIVE).equals(record.livemode())`.

## Where are the Java quickstart and the API reference?

Start with the quickstart: it carries every file this page excerpts, in the order you write them.

- Quickstart

  **[Java quickstart](https://esigncomply.com/docs/quickstart/java)**

  Step by step, from install to your first sealed test record, with every file and the output of each step.

- Reference

  **[API reference](https://esigncomply.com/docs/api)**

  Every endpoint, field and error code. Sessions, records and documents are the three this page uses.

- Guide

  **[Server confirmation](https://esigncomply.com/docs/guides/server-confirmation)**

  The one place access is granted: what to compare, and the webhook that backs the check up.

Verifiable

## What does Esign Comply record for a signature in Java?

The same record on every stack and platform. Your Java code creates the session and confirms the record, and the browser SDK reports what happened on the page. Esign Comply seals the result where your code cannot change it. The record itself is described on [Evidence and verification](https://esigncomply.com/product/evidence).

- **Observed and asserted fields**

  Every field is tagged. Observed is what the browser SDK and the API saw: the box unchecked at load, the tick from a trusted user event, the notice text, the terms version by hash, the server time. Asserted is what your app said, such as the user's email.

- **A signed receipt**

  `complete()` returns a receipt signed with ES256, using keys you do not hold. Your server stores it next to the user, and `GET /v1/records/{id}/receipt` returns it again.

- **An external timestamp**

  An outside authority timestamps the hash of every live record (RFC 3161), so the time on the record does not rest on your clock or on ours.

- **An offline verifier**

  Each record has an evidence report (PDF) and an evidence package (ZIP). Anyone you send the package to checks the acceptance with the open-source `esigncomply-verify`, without an account.

[How sealing and verification work](https://esigncomply.com/product/evidence) · [Observed and asserted, in the docs](https://esigncomply.com/docs/concepts/observed-and-asserted) · [The offline verifier](https://esigncomply.com/docs/sdk/verify)

Record

`rec_Z4m8`

simple · L1

Recorded

Written durably, receipt signed with ES256

Timestamped

External RFC 3161 token over the record hash

Anchored

Public anchor pending

Checkbox changed by a trusted user event · observed

Terms of Service, version dv_3kT9 · observed

Server time 2026-11-21T15:03:20.291Z · observed

Signer email dana@example.org · asserted

record_hash sha256:5be7… · example record

## Questions about e-signatures in Java

### Is there an Esign Comply SDK for Java?

No. The server SDK exists for Node.js only. A Java server calls the REST API directly with the secret key, and the quickstart does it with `java.net.http.HttpClient` in one method. The only jar beside the JDK is Gson, for the JSON.

### Where do I create the session in Java?

In the method `ceremony`, which the handler calls for `POST /api/ceremony`, with a `POST` to `/v1/sessions` that carries the secret key and an `Idempotency-Key`. It puts the pinned versions in the signed cookie and returns only the client token, the API URL and the documents.

### Why does the quickstart pin the JDK HttpClient to HTTP/1.1?

Because that is the code that was run. Over plain http the JDK client asks for HTTP/2 with an `Upgrade: h2c` header, and the test API closed such a connection: `send` threw an `IOException`. With `HTTP_1_1` pinned the same call was answered `200`. Calls over https were not run.

### Which JSON library does plain Java need?

One of your choice: the JDK has no JSON parser. The quickstart uses Gson 2.15.0, a single jar of 316 KB with nothing else on the classpath in the test. It reads the API's snake_case fields into records with one setting. Jackson does the same job, as the Spring Boot page shows.

### When should I use Spring Boot instead of plain Java?

When your app already runs on it, or needs what it brings: a session, JSON binding and Tomcat. Its page shows the same two API calls with `RestClient`. Plain Java fits a small service with no framework, where the JDK's own client and server are enough.

### Other stacks

- [Spring Boot](https://esigncomply.com/spring-boot)
- [Go](https://esigncomply.com/go)
- [.NET](https://esigncomply.com/dotnet)

### Platforms used with Java

- [Railway](https://esigncomply.com/railway)
- [Render](https://esigncomply.com/render)
- [Google Cloud Run](https://esigncomply.com/google-cloud-run)

[All stacks](https://esigncomply.com/stacks) · [All platforms](https://esigncomply.com/platforms) · [Clickwrap API](https://esigncomply.com/clickwrap) · [E-signature API](https://esigncomply.com/sign)

## Call the API from the Java you already run. Leave the record to us.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/java)

Free plan: 10 live signatures a month and a full test mode. No card required.

Java is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Java is from Java's documentation or from a test run, as marked, on November 26, 2026. `/java.md` is this page as Markdown.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.

---

Esign Comply is the e-signature API and clickwrap API for developers who build their own signing flow in their own UI: it supplies the ceremony rules as a generated prompt for AI coding tools, records events in direct browser ceremonies, and seals independent, verifiable evidence.
