Gumdrop

Gumdrop HTTP Server & Client

Gumdrop provides a comprehensive HTTP implementation supporting HTTP/3, HTTP/2, and HTTP/1.x. Applications compose an HttpServer with listeners and an HttpStreamHandler that binds an HttpRequestHandler to each stream - see Application composition. Higher-level stacks attach as handlers: servlet container (ServletRequestHandler), WebDAV (WebDAVRequestHandler).

Contents

HTTP versions

Gumdrop supports HTTP/3, HTTP/2, HTTP/1.1, and HTTP/1.0, with automatic version detection and negotiation. Originally built to support HTTP/1.1 as a native protocol, Gumdrop was first adapted to use the SPDY protocol developed by Google, and then, as that was deprecated and consensus established on the newer HTTP/2 protocol, Gumdrop embraced the efficiency and extensibility of the latter. With the standardisation of HTTP/3 over QUIC, Gumdrop now supports the full spectrum of modern HTTP.

HTTP/3

HTTP/3 (RFC 9114) runs over QUIC instead of TCP. QUIC provides built-in TLS 1.3 encryption, multiplexed streams without head-of-line blocking, and faster connection establishment (often 0-RTT). HTTP/3 is configured via a separate Http3Listener that listens on a UDP port. See HTTP/3 and QUIC below for details.

HTTP/2

Complete HTTP/2 implementation (RFC 7540) with multiplexing and header compression. HTTP/2 can be negotiated via ALPN during TLS handshake or via cleartext upgrade (h2c). See HTTP/2 Support below for details.

HTTP/1.1

Full HTTP/1.1 support including:

HTTP/1.0

Basic HTTP support for legacy clients. Connections are closed after each request/response unless explicitly kept alive.

HTTP/3 and QUIC

HTTP/3 is the latest major version of the Hypertext Transfer Protocol. Unlike HTTP/1.1 and HTTP/2, which run over TCP, HTTP/3 uses QUIC (RFC 9000) as its transport layer. QUIC provides:

Architecture

Gumdrop’s HTTP/3 support is built on the pure-Java QUIC stack in org.bluezoo.gumdrop.quic with TLS 1.3 from the in-tree engine (org.bluezoo.gumdrop.tls). The QUIC layer handles connection management, stream multiplexing, and congestion control, while HTTP/3 framing (HEADERS, DATA, QPACK) is processed by Gumdrop’s Http3ServerHandler and H3Stream classes.

QUIC versions 1 (RFC 9000) and 2 (RFC 9369) are both supported. Version 2 differs from version 1 only in details such as the Initial salt and key-derivation labels, so that middleboxes cannot ossify on version 1. A server accepts either, advertises both in its version_information transport parameter (RFC 9368), and in compatible version negotiation moves a client to the first version in its own preference order that the client also offers. A client opens in version 1, which servers most often parse, and offers version 2 as a compatible version. A datagram of any other version that is large enough to start a connection (at least 1200 bytes) is answered with a Version Negotiation packet (RFC 9000 section 6.1) listing the supported versions, at most 100 per second; smaller datagrams are dropped silently. A client that receives a valid Version Negotiation packet listing no version it supports abandons the attempt with a QuicVersionNegotiationException.

From the application’s perspective, HTTP/3 is transparent. The same HttpRequestHandler interface is used regardless of whether the request arrived over HTTP/3, HTTP/2, or HTTP/1.1. The only visible difference is the HTTP version reported by HttpResponse.getVersion().

Gumdrop 3 uses a single handler (or decorator chain) on HttpServer, not a handler factory - see Application composition.

Configuration

HTTP/3 is configured by adding an Http3Listener to an HttpServer. Because QUIC uses UDP, the HTTP/3 listener is independent of the TCP-based Http2Listener and can coexist with it:

TlsConfig tls = TlsConfig.pem(Path.of("etc/tls/cert.pem"), Path.of("etc/tls/key.pem"));
// PKCS#12 / JKS: see tls.html#keystores

HttpServer server = HttpServer.compose()
    // Wires both HTTP/1.1 + HTTP/2 over TCP and HTTP/3 over QUIC on
    // the same port, sharing the same TLS material.
    .secureEndpoint(443, tls)
    .streamHandler(new ServletRequestHandler(container))
    .server();

Gumdrop gumdrop = Gumdrop.boot();
gumdrop.addServer(server);

secureEndpoint is shorthand for adding a secure Http2Listener and an Http3Listener yourself, which you do when they need different settings:

HttpServer server = HttpServer.compose()
    .listener(new Http2Listener().port(443).secure(true).tls(tls))
    .listener(new Http3Listener().port(443).tls(tls).requireRetry(true))
    .streamHandler(handler)
    .server();

Note that the TCP and QUIC listeners can share the same port number (443 is conventional) because they use different transport protocols (TCP vs UDP).

Server identity

All secure listeners use the same in-tree TLS stack and take their identity from a TlsConfig: PEM files with TlsConfig.pem(cert, key), or a Java keystore with TlsConfig.keystore(file, password). Use the same identity on co-located TCP and QUIC listeners so Alt-Svc upgrades do not trigger certificate warnings, which is what secureEndpoint does. See TLS, DTLS and QUIC: co-located HTTPS and HTTP/3 and using Java keystores.

Alt-Svc advertisement

When an HttpServer has both TCP and QUIC listeners, it automatically computes an Alt-Svc response header and injects it into HTTP/1.1 and HTTP/2 responses served by the TCP listener. This tells clients that HTTP/3 is available:

alt-svc: h3=":443"; ma=86400

To advertise something else, set the value on a listener with Http2Listener.altSvc(String).

Clients that support HTTP/3 (all major browsers, curl, etc.) will attempt to use QUIC on subsequent requests. Alt-Svc is the fallback way to advertise HTTP/3, for first contact with clients that did not find a DNS HTTPS record (RFC 9460) with alpn=h3,h2 for your host name; publish both where you can, since the HTTPS record lets a client use HTTP/3 from its very first request. Gumdrop's own client looks at the HTTPS record first (see Choosing HTTP/3 or TCP). If the QUIC connection fails or is not supported by the network, clients fall back to HTTP/2 or HTTP/1.1 transparently.

Protocol compliance

The server validates incoming requests per RFC 9114:

On the client side:

Http3Listener settings

Besides the common listener options (port, addresses, connection limits, timeouts, see Security), Http3Listener has:

HTTP/2

Gumdrop's HTTP/2 implementation provides all mandatory features of RFC 7540 plus several optional features.

Frame types

All HTTP/2 frame types are supported:

HPACK header compression

Gumdrop includes a complete HPACK implementation (RFC 7541) for HTTP/2 header compression:

The HPACK encoder and decoder maintain separate dynamic tables for each direction of communication, with configurable maximum table sizes.

Frame padding

For security-sensitive applications, HTTP/2 frame padding can be enabled to obscure message sizes. Padding adds random-length padding to DATA, HEADERS, and PUSH_PROMISE frames (RFC 7540 Section 6.1).

new Http2Listener().port(443).secure(true).tls(tls).framePadding(64);

The value is the padding length in bytes (0 to 255, default 0, which disables it).

Connection management (HTTP/2)

Server handler API

Gumdrop provides an event-driven, non-blocking API for building HTTP servers. The API abstracts away HTTP version details (HTTP/3, HTTP/2, and HTTP/1.1), allowing handlers to focus on application logic while the framework handles framing, header compression, flow control, and connection management.

Core interfaces

The server handler API centres on three interfaces:

Event sequence

Request handlers receive events in a well-defined order:

version()              // HTTP version
method(HttpMethod)     // request method
target(ByteBuffer)     // request target (path and query)
scheme(ByteBuffer)     // scheme (HTTP/2 and HTTP/3)
authority(ByteBuffer)  // authority / Host
contentType(ContentType)               // if present
contentDisposition(ContentDisposition) // if present
longHeader(name, long) // numeric fields, e.g. content-length
dateHeader(name, Instant) // date fields, e.g. if-modified-since
header(name, value)    // every other field line, one event per line
endHeaders()           // header section complete
bodyContent(ByteBuffer) // zero or more body chunks
header(name, value)    // trailer fields (a header event after endHeaders)
endMessage()           // request complete

For requests without a body (GET, HEAD, etc.) endHeaders() is followed directly by endMessage(). A malformed message is reported as error(HttpError, String); if the exchange ends without endMessage() because of a transport failure (RST_STREAM, connection closed), failed(Exception) is called instead. Header values passed to header(...) are read-only views valid only during the call: copy them if you keep them. A response uses the same events, with status() and reason() in place of method() and target().

Trailer fields

Trailer fields (RFC 9110 section 6.5) are not a separate event. They arrive as header(name, value) events after bodyContent() (a handler tells a trailer from a header by whether endHeaders() has been seen), and the body ends at the first such event or at endMessage(). They are typed like header fields where that makes sense: Date, Expires and Last-Modified arrive as dateHeader, and Retry-After as longHeader (seconds) or dateHeader (HTTP-date). Fields that must be known before the content (framing, routing, request modifiers and authentication; RFC 9110 section 6.5.1) are dropped, and a pseudo-header in an HTTP/2 or HTTP/3 trailer section is malformed (reported as error). A client's HttpResponseHandler receives response trailers the same way.

Sending responses

The HttpResponse interface provides methods for building responses:

status(code)           // 1xx, then endHeaders(), any number of times (optional)
status(code)           // the final status (200 if omitted)
header(name, value)    // one call per field
longHeader(name, n)    // a field with an integer value, e.g. content-length
dateHeader(name, instant) // a field with an HTTP-date, e.g. last-modified
contentType(type)      // a ContentType
contentDisposition(d)  // a ContentDisposition
endHeaders()           // send the header section now (optional)
bodyContent(buf)       // zero or more body chunks; the first one ends the
                       // header section if endHeaders() has not been called
header(name, value)    // trailer fields, after the body began (optional)
endMessage()           // finish the response (required)

The events mirror those a received message is made of, in the same order. Nothing is sent until the header section ends, so a response with no body (a status, any fields and endMessage()) goes out as a single header section that also ends the stream. A field given after the body has begun is a trailer field; fields that must be known before the content (framing, routing and authentication fields) are rejected with IllegalArgumentException.

Call endHeaders() explicitly only when the header section must go out immediately, as for a streaming response. An interim (1xx) response is sent by giving a 1xx status(), any fields, then endHeaders(), before the final status():

response.status(103);                 // 103 Early Hints
response.header("link", "</styles/main.css>; rel=preload; as=style");
response.endHeaders();                // sends the interim response

response.status(200);                 // the final response follows
response.contentType(new ContentType("text", "html", null));
response.longHeader("content-length", body.remaining());
response.bodyContent(body);
response.header("x-checksum", checksum);  // a trailer field
response.endMessage();

A content-length set on an HTTP/2 or HTTP/3 response is sent as given, and must equal the body bytes (RFC 9113 section 8.1.1, RFC 9114 section 4.1.2). If the body runs past it, bodyContent throws IllegalStateException; if the response ends short of it, or past it, the stream is reset with an internal error rather than finished as a malformed message. The length is not checked for HEAD, 204 or 304 responses.

Example: hello world handler

public class HelloHandler extends DefaultHttpRequestHandler {
    private final HttpResponse response;
    private HttpMethod method;

    public HelloHandler(HttpResponse response) {
        this.response = response;
    }

    @Override
    public void method(HttpMethod method) {
        this.method = method;
    }

    @Override
    public void endHeaders() {
        if (method == HttpMethod.GET) {
            response.status(200);
            response.contentType(new ContentType("text", "plain", null));
            response.bodyContent(
                ByteBuffer.wrap("Hello, World!".getBytes()));
            response.endMessage();
        }
    }
}

Request routing

A single HttpRequestHandler sees the request line and header fields first, so routing decisions based on path, method, or other criteria happen in its endHeaders() event, once the fields it needs have been remembered. The router then creates the delegate and replays the events it has seen to it:

public class RoutingHandler extends DefaultHttpRequestHandler {
    private final HttpResponse response;
    private HttpMethod method;
    private ByteBuffer target;
    private HttpRequestHandler delegate;

    public RoutingHandler(HttpResponse response) {
        this.response = response;
    }

    @Override
    public void method(HttpMethod method) {
        this.method = method;
    }

    @Override
    public void target(ByteBuffer target) {
        // read-only view valid only during this call: copy it
        this.target = ByteBuffer.allocate(target.remaining()).put(target);
        this.target.flip();
    }

    @Override
    public void endHeaders() {
        String path = StandardCharsets.UTF_8.decode(target.duplicate()).toString();

        if (path.startsWith("/api/")) {
            delegate = new ApiHandler(response);
        } else if (path.startsWith("/static/")) {
            delegate = new StaticFileHandler(response, documentRoot);
        } else {
            delegate = new DefaultHandler(response);
        }
        delegate.method(method);
        delegate.target(target);
        delegate.endHeaders();
    }

    @Override
    public void bodyContent(ByteBuffer data) {
        delegate.bodyContent(data);
    }

    @Override
    public void endMessage() {
        delegate.endMessage();
    }
}

Running the server

Compose the handler onto the server:

HttpServer server = HttpServer.compose()
        .listener(new Http2Listener().port(8080))
        .streamHandler(new HttpStreamHandler() {
            @Override
            public HttpRequestHandler openStream(HttpResponse response) {
                return new RoutingHandler(response);
            }
        })
        .server();

Gumdrop gumdrop = Gumdrop.boot();
gumdrop.addServer(server);

Authentication

If a Realm is configured with HttpServer.compose().realm(realm), authentication is performed automatically before your handler sees the request, and failed attempts are counted towards the listener's lockout (see Security). The authenticated principal is available via HttpResponse.getPrincipal(). A custom HttpAuthenticationProvider can be set on a listener with .authenticationProvider(...).

Alternatively, a handler can perform authentication itself:

public class AuthHandler extends DefaultHttpRequestHandler {
    private final HttpResponse response;
    private String auth;

    public AuthHandler(HttpResponse response) {
        this.response = response;
    }

    @Override
    public void header(String name, ByteBuffer value) {
        if ("authorization".equals(name)) {
            auth = StandardCharsets.UTF_8.decode(value).toString();
        }
    }

    @Override
    public void endHeaders() {
        if (!isValidAuth(auth)) {
            response.status(HttpStatus.UNAUTHORIZED.code);
            response.header("www-authenticate", "Bearer");
            response.endMessage();
            return;
        }
        // continue with the normal handling...
    }
}

HTTP/2 server push

For HTTP/2 connections, handlers can initiate server push to proactively send resources to the client:

@Override
public void authority(ByteBuffer authority) {
    // copy: the buffer is only valid during this call
    this.authority = StandardCharsets.UTF_8.decode(authority).toString();
}

@Override
public void endHeaders() {
    // Push a stylesheet that we know the client will need
    // The server adds :scheme and :authority of the current request
    response.startPushPromise(HttpMethod.GET, "/styles/main.css");
    response.header("accept", "text/css");
    boolean pushed = response.endPushPromise();
    if (pushed) {
        // Push was accepted; the pushed stream will be processed
        // by your HttpStreamHandler like any other request
    }
    
    // Continue with the normal response...
}

Server push returns false for HTTP/1.x connections or if the client has disabled push via settings.

Connection information

The HttpResponse provides access to connection details:

Streaming responses

For server-sent events or other streaming scenarios:

public class StreamHandler extends DefaultHttpRequestHandler {
    private final HttpResponse response;

    public StreamHandler(HttpResponse response) {
        this.response = response;
    }
    
    @Override
    public void endHeaders() {
        response.status(200);
        response.header("content-type", "text/event-stream");
        response.endHeaders();  // send the header section now
        
        // The response field stays valid for async sends
        eventEmitter.subscribe(new EventListener() {
            public void onEvent(Event event) {
                response.bodyContent(
                    ByteBuffer.wrap(event.toSSE().getBytes()));
            }
        });
    }
}

Flow control and backpressure

When a handler produces response data faster than the network can deliver it, or receives request body data faster than it can process it, backpressure prevents unbounded buffering. HttpResponse provides three methods that work uniformly across HTTP/1.1, HTTP/2, and HTTP/3:

// Streaming a large file with write-side backpressure
response.status(200);
response.endHeaders();
sendNextChunk(response, channel);

void sendNextChunk(final HttpResponse response, final ReadableByteChannel src) {
    ByteBuffer buf = ByteBuffer.allocate(8192);
    int n = src.read(buf);
    if (n > 0) {
        buf.flip();
        response.bodyContent(buf);
        response.onWritable(new Runnable() {
            public void run() {
                sendNextChunk(response, src);
            }
        });
    } else {
        response.endMessage();
    }
}
// Throttling request body consumption with read-side backpressure
public void bodyContent(ByteBuffer data) {
    if (!processor.ready()) {
        response.pauseRequestBody();
        processor.onReady(new Runnable() {
            public void run() {
                response.resumeRequestBody();
            }
        });
        return;
    }
    processor.consume(data);
}

For HTTP/2 and HTTP/3, backpressure is per-stream: pausing one stream does not affect other streams on the same connection. For HTTP/1.1, it operates at the connection level via TCP flow control.

Error handling

Use cancel() to abort a stream on error:

@Override
public void bodyContent(ByteBuffer data) {
    if (data.remaining() > MAX_BODY_SIZE) {
        response.status(HttpStatus.PAYLOAD_TOO_LARGE.code);
        response.endMessage();
        response.cancel();  // abort the stream
    }
}

Protocol upgrades

HTTP/2 cleartext upgrade (h2c)

For non-TLS connections, HTTP/2 can be negotiated via the HTTP/1.1 Upgrade mechanism. The client sends:

GET / HTTP/1.1
Host: example.com
Connection: Upgrade, HTTP2-Settings
Upgrade: h2c
HTTP2-Settings: AAMAAABkAARAAAAAAAIAAAAA

If the server supports HTTP/2, it responds with 101 Switching Protocols and both sides switch to HTTP/2 framing:

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: h2c

The HTTP2-Settings header contains base64url-encoded SETTINGS frame payload, allowing the client to communicate initial settings before the upgrade completes.

Connection management

Gumdrop provides several mechanisms for managing HTTP/1.1 persistent connections efficiently (RFC 9112 section 9):

Idle connection timeout

Http2Listener.idleTimeoutMs(long) configures how long a persistent connection can remain idle before the server closes it (RFC 9112 section 9.8). The timer resets each time data is received. A value of 0 disables the timeout.

Requests per connection

Http2Listener.maxRequestsPerConnection(int) limits how many requests are served on a single persistent connection. When the limit is reached, the server adds a Connection: close header to the response, signalling the client to close the connection after the current exchange (RFC 9112 section 9.6). A value of 0 means unlimited.

Expect: 100-continue

When a client sends an Expect: 100-continue header, the server sends an interim 100 Continue response before the client transmits the request body. This avoids wasting bandwidth on large uploads the server would ultimately reject (RFC 9110 section 10.1.1).

OPTIONS * and TRACE

The server handles OPTIONS * requests directly, returning a 200 OK with an Allow header listing the supported methods (RFC 9110 section 9.3.7). The TRACE method is supported but disabled by default for security; call traceMethodEnabled(true) on the listener to enable it (RFC 9110 section 9.3.8).

Listener and server settings

All settings are fluent methods. Server-wide ones are on HttpServer.compose() or the server; the rest are on the listener, and the listener value wins when both are set.

HttpServer settings

Origin caching (RFC 9111)

Static resources served by the default servlet (and the servlet getLastModified hook) emit ETag and Last-Modified validators and honour If-None-Match / If-Modified-Since with 304 Not Modified when appropriate (RFC 9110 section 13, RFC 9111). Shared/intermediary cache behaviour is not implemented; this is origin-server correctness for conditional GET and HEAD.

Http2Listener settings

Http2Listener is the TCP listener for HTTP/1.1 and HTTP/2. It has the common listener options (port, addresses, connection limits, timeouts; see Security) and:

Combined HTTP/3, HTTP/2 and HTTP/1.1

A typical production configuration exposes both TCP (HTTP/1.1, HTTP/2) and QUIC (HTTP/3) on the same port number: the TCP listener handles traditional connections while the QUIC listener handles HTTP/3 on UDP. The server automatically sets the Alt-Svc header on TCP responses so clients can discover and migrate to HTTP/3:

HttpServer server = HttpServer.compose()
    .secureEndpoint(443, TlsConfig.keystore(Path.of("keystore.p12"), "changeit"))
    .streamHandler(handler)
    .server();

Authentication

Gumdrop supports HTTP authentication methods:

Authentication is configured via an HttpAuthenticationProvider which can be shared across multiple services or customised per service. It is integrated into the centralised org.bluezoo.gumdrop.auth.Realm-based facility for managing authentication and authorisation across all services running in the framework.

HTTP client

Gumdrop includes a non-blocking HTTP client that shares the same event-driven architecture as the server. The client supports HTTP/3, HTTP/2, and HTTP/1.1 with automatic protocol negotiation.

SelectorLoop affinity

When an HTTP client connection is initiated by a Gumdrop server connection, it can be assigned to the same Gumdrop worker SelectorLoop as is used by used by the server connection. This provides several advantages:

This makes the HTTP client particularly well-suited for server-side use cases such as proxying, service-to-service communication, and telemetry export where the client operates within the context of an existing Gumdrop server.

The existing OpenTelemetry implementation within Gumdrop uses this exact mechanism for efficiency, and server processes that need to call REST endpoints, for instance, can easily benefit from high performance asynchronous non-blocking connections to them via this feature.

Features

Hostname resolution

Give the client a host name and it resolves it through Gumdrop's asynchronous DnsResolver on the connection's own selector loop; no blocking InetAddress lookup is made. Use dnsResolver(DnsResolver) to supply your own resolver, for example one using DNS over TLS. See DNS: hostname resolution in every Gumdrop client. Setting blockPrivateAddresses(true) refuses names that resolve to private addresses, which protects a server that fetches URLs on behalf of users from being pointed at internal services.

Connection pooling

connectionPool(ClientEndpointPool) enables endpoint reuse with SelectorLoop affinity. Pool targets are keyed by (host, port, secure, loop). When a pooled connection is available, the client skips the connect/TLS handshake and reuses the existing endpoint.

TLS and certificate pinning

secure(true) selects TLS over TCP, and HTTP/3 is always TLS 1.3. Pass trust material and any client certificate with tls(TlsConfig). For SHA-256 fingerprint pinning, put a PinnedCertTrustManager in the config:

HttpClient client = new HttpClient("example.com", 443)
    .secure(true)
    .tls(new TlsConfig().trustManager(new PinnedCertTrustManager("ab:cd:...")));

Choosing HTTP/3 or TCP

Unless you permit only HTTP/3 (see Permitted versions), which goes straight to QUIC, the client chooses the transport automatically when it connects to a host name, in three steps:

  1. DNS HTTPS record (first choice). The client asks the resolver for the host's HTTPS record (RFC 9460). If it advertises h3 in its ALPN list, the client connects over QUIC, using the record's port if it has one. This costs one DNS lookup and no failed TCP connection, so HTTP/3 is used from the very first request. Any Encrypted Client Hello configuration in the record is picked up at the same time. Disable it with dnsHttpsRecordEnabled(false). It is skipped for literal IP addresses and localhost, where there is nothing to look up.
  2. Cached Alt-Svc (fallback). If there is no usable HTTPS record, the client checks an in-memory cache of Alt-Svc advertisements remembered from earlier responses from this origin, and uses HTTP/3 if one is still valid.
  3. TCP. Otherwise it connects over TCP and negotiates HTTP/2 with ALPN (or h2c, or HTTP/1.1).

If a QUIC attempt chosen in step 1 or 2 fails, or has not established within three seconds (quicHandshakeTimeoutMs(long); 0 disables the deadline), the client abandons it and connects over TCP, so a network that blocks UDP, or a stale record, costs a delay and not a failed request. WebSocketClient, ConnectIpClient and ConnectUdpClient (see MASQUE) take the same versions(...) list and quicHandshakeTimeoutMs(long), discover HTTP/3 the same way and fall back to TCP the same way. When only HTTP/3 is permitted there is nothing to fall back to, and a QUIC attempt that has not established within the deadline fails with an error instead of waiting indefinitely.

Alt-Svc is also how a client learns about HTTP/3 when the origin publishes no HTTPS record: with altSvcEnabled(true) (the default), an h3 Alt-Svc header on a response over HTTP/1.1 or HTTP/2 is cached for later connections and, on the connection that received it, the client can move over to HTTP/3. This is why the server injects Alt-Svc, but publishing an HTTPS record with alpn=h3,h2 in DNS gives clients, Gumdrop's included, a better first connection.

Permitted versions

versions(HttpVersion...) sets which HTTP versions the client may use. The default is HTTP_3, HTTP_2_0 and HTTP_1_1. The client always prefers the highest permitted version, so the order you list them in does not matter, and discovery only considers versions you permit:

PermittedBehaviour
default (all three)discover HTTP/3, fall back to TCP, then HTTP/2 or HTTP/1.1 by ALPN
HTTP_3 onlyQUIC straight away: no discovery, no fallback
HTTP_2_0, HTTP_1_1never QUIC (the HTTPS record is still read for other parameters such as ECH)
HTTP_2_0 onlyTLS offers only h2; over cleartext, HTTP/2 with prior knowledge
HTTP_1_1 onlyHTTP/1.1; no h2 offered, no h2c upgrade

HTTP_1_0 is not accepted: the client speaks HTTP/1.1. h2WithPriorKnowledge(true) makes a cleartext connection start HTTP/2 without upgrading, and requires HTTP_2_0 to be permitted.

Other settings

Usage (HTTP/2 and HTTP/1.1)

In the client examples on this page, gumdrop is the Gumdrop instance returned by Gumdrop.boot(); a client is given it when it connects.

final HttpClient client = new HttpClient("example.com", 443).secure(true);

client.connect(gumdrop, new HttpClientHandler() {
    public void onConnected(Endpoint endpoint) {
        HttpRequest request = client.get("/api/data", new DefaultHttpResponseHandler() {
            public void status(int code) {
                System.out.println("Status: " + code);
            }
            public void bodyContent(ByteBuffer data) {
                // Process response body
            }
            public void endMessage() {
                System.out.println("Response complete");
                client.close();
            }
            public void failed(Exception ex) {
                ex.printStackTrace();
            }
        });
        request.header("Accept", "application/json");
        request.endMessage();
    }
    public void onSecurityEstablished(SecurityInfo info) { }
    public void onError(Exception cause) { cause.printStackTrace(); }
    public void onDisconnected() { }
});

Usage (HTTP/3)

There is nothing to enable: the example above uses HTTP/3 automatically whenever the host advertises it, through a DNS HTTPS record or a cached Alt-Svc (see Choosing HTTP/3 or TCP), and otherwise uses HTTP/2 or HTTP/1.1. The request and response code is the same either way. A host that publishes neither is reached over TCP, and the client moves to HTTP/3 only once a response has advertised it.

Permit only HTTP/3 to force it when you already know the server speaks it, for example an internal service or a test. The client then skips discovery, connects with QUIC and ALPN “h3” straight away, and fails if the server does not answer, with no fallback to TCP:

final HttpClient client = new HttpClient("example.com", 443).versions(HttpVersion.HTTP_3);

client.connect(gumdrop, new HttpClientHandler() {
    public void onConnected(Endpoint endpoint) {
        HttpRequest request = client.get("/api/data", responseHandler);
        request.header("Accept", "application/json");
        request.endMessage();
    }
    public void onSecurityEstablished(SecurityInfo info) { }
    public void onError(Exception cause) { cause.printStackTrace(); }
    public void onDisconnected() { }
});

Receiving server push (HTTP/2)

A server may promise to push a resource (RFC 9113 section 8.4). The promised request reaches the client as the same events a server handler receives: method, target, scheme, authority, the fields, endHeaders and endMessage. To take part, override HttpResponseHandler.pushPromise() and return a PushPromiseHandler. Once the promised request has been delivered, its pushedResponse() returns the HttpResponseHandler for the pushed response, or null to refuse the push. The default pushPromise() returns null, which refuses every push with RST_STREAM (REFUSED_STREAM). A promised request that is malformed, for example one with no :path, is reset with PROTOCOL_ERROR and the handler is not called.

HttpRequest request = client.get("/index.html", new DefaultHttpResponseHandler() {
    // ... the events of the main response ...

    @Override
    public PushPromiseHandler pushPromise() {
        return new PushPromiseHandler() {
            private boolean stylesheet;

            @Override
            public void target(ByteBuffer target) {
                String path = StandardCharsets.ISO_8859_1.decode(target).toString();
                stylesheet = path.endsWith(".css");
            }

            @Override
            public HttpResponseHandler pushedResponse() {
                if (!stylesheet) {
                    return null; // refuse
                }
                return new DefaultHttpResponseHandler() {
                    @Override
                    public void status(int code) {
                        System.out.println("pushed: " + code);
                    }

                    @Override
                    public void bodyContent(ByteBuffer data) {
                        // consume the pushed body
                    }
                };
            }
        };
    }
});
request.endMessage();

Request bodies and trailers

A request is built with the same calls and types as the events a server receives: header, longHeader, dateHeader, contentType and contentDisposition, then bodyContent(ByteBuffer) any number of times and endMessage(). Nothing is written until it is needed; the header section goes out with the first piece of body, or with endMessage() if there is none. A field given with request.header(...) after the body has begun is a trailer: it is sent after the last chunk on HTTP/1.1 (so the body is chunked) and as a final HEADERS frame on HTTP/2 and HTTP/3.

The request and response APIs are identical regardless of the underlying protocol version. The only difference is how the client is configured before connecting.

All handler callbacks are invoked on the client connection’s assigned worker thread. Long-running operations within handlers should be offloaded to avoid blocking the SelectorLoop.


← Back to Main Page | File server and WebDAV | WebSocket service and client | MASQUE | SMTP Server & Client | IMAP Server | POP3 Server | NNTP Server | DNS | Telemetry

Gumdrop HTTP Server