HTTP headers

suggest change

Every HTTP request and response carries headers: Name: value lines that describe the message (Content-Type, Content-Length), give the client's preferences (Accept, Accept-Language), carry credentials (Authorization, Cookie) and control caching (Cache-Control, ETag). Two rules apply to all of them:

That's why Java's header APIs map a name to a List<String> and look names up without regard to case. This article uses the JDK's java.net.http.HttpClient (Java 11+) on the client side and the built-in com.sun.net.httpserver.HttpServer on the server side. No dependencies are needed. Each example starts its own server on a free port (new InetSocketAddress("localhost", 0)), so you can run it as is with java Example.java. All output below comes from JDK 25.

For general request/response handling see REST APIs. For the older API see HttpURLConnection.

Setting request headers

HttpRequest.Builder has three methods for headers:

Method Behavior
header(name, value) Adds a value. Calling it twice with the same name sends two values
headers(n1, v1, n2, v2, ...) Adds several name/value pairs at once
setHeader(name, value) Replaces all earlier values of that header

The server in this example sends back the headers it received:

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.TreeMap;

public class EchoHeaders {
    public static void main(String[] args) throws Exception {
        // A tiny server that sends back the request headers it received
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/echo", exchange -> {
            StringBuilder sb = new StringBuilder();
            new TreeMap<>(exchange.getRequestHeaders())
                .forEach((name, values) -> sb.append(name).append(": ").append(values).append('\n'));
            byte[] body = sb.toString().getBytes(StandardCharsets.UTF_8);
            exchange.sendResponseHeaders(200, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.start();
        int port = server.getAddress().getPort();

        HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/echo"))
            .header("Accept", "application/json")
            .header("Accept-Language", "en-US")
            .header("X-Trace", "first")
            .header("X-Trace", "second")             // header() appends
            .headers("X-Client", "demo", "X-Version", "3") // name/value pairs
            .setHeader("Accept-Language", "pl-PL")   // setHeader() replaces
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.print(response.body());
        server.stop(0);
    }
}

Output (the port changes from run to run):

Accept: [application/json]
Accept-language: [pl-PL]
Host: [localhost:49211]
User-agent: [Java-http-client/25.0.4.1]
X-client: [demo]
X-trace: [first, second]
X-version: [3]

A few things to note:

Leave out .version(HTTP_1_1) and the client's default is HTTP/2. On a plain http:// URL it then tries to upgrade the connection, which adds more headers to the request:

Connection: [Upgrade, HTTP2-Settings]
Http2-settings: [AAEAAEAAAAIAAAAAAAMAAAAAAAQBAAAAAAUAAEAAAAYABgAA]
Upgrade: [h2c]

Over https:// HTTP/2 is negotiated during the TLS handshake, so no upgrade headers are sent.

Restricted and invalid headers

The client manages some headers itself and won't let you set them. It also checks names and values against the HTTP grammar. The check rejects a value containing CR or LF, which protects you from header injection when a value comes from user input:

import java.net.URI;
import java.net.http.HttpRequest;

public class RestrictedHeaders {
    static void tryHeader(String name, String value) {
        try {
            HttpRequest.newBuilder(URI.create("http://example.com/")).header(name, value);
            System.out.println("OK       " + name);
        } catch (IllegalArgumentException e) {
            String reason = e.getMessage().split(":")[0]; // drop the echoed value
            System.out.println("REJECTED " + name + " -> " + reason);
        }
    }

    public static void main(String[] args) {
        tryHeader("X-Api-Key", "abc123");
        tryHeader("Host", "other.example.com");
        tryHeader("Connection", "close");
        tryHeader("Content-Length", "10");
        tryHeader("Upgrade", "h2c");
        tryHeader("Bad Name", "x");
        tryHeader("X-Injected", "value\r\nSet-Cookie: evil=1");
    }
}

Output:

OK       X-Api-Key
REJECTED Host -> restricted header name
REJECTED Connection -> restricted header name
REJECTED Content-Length -> restricted header name
REJECTED Upgrade -> restricted header name
REJECTED Bad Name -> invalid header name
REJECTED X-Injected -> invalid header value

The restricted set is Connection, Content-Length, Expect, Host and Upgrade. Content-Length comes from the BodyPublisher you pass to POST()/PUT(). If you really need to set Host or Connection (for example, to test a virtual host by IP address), allow them with a system property:

java -Djdk.httpclient.allowRestrictedHeaders=host,connection RestrictedHeaders.java

With that property, Host and Connection print OK. Content-Length and Upgrade are still rejected.

Reading response headers

HttpResponse.headers() returns an immutable java.net.http.HttpHeaders. Its methods:

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class ResponseHeaders {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/", exchange -> {
            byte[] body = "{\"ok\":true}".getBytes(StandardCharsets.UTF_8);
            Headers h = exchange.getResponseHeaders();
            h.set("Content-Type", "application/json; charset=utf-8");
            h.set("Cache-Control", "no-store");
            h.add("Set-Cookie", "session=abc123; Path=/; HttpOnly; Secure");
            h.add("Set-Cookie", "theme=dark; Path=/; Max-Age=31536000");
            h.set("X-Request-Id", "7f3c9a");
            exchange.sendResponseHeaders(200, body.length); // also sets Content-length
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.start();
        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/");

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> resp = client.send(HttpRequest.newBuilder(uri).build(),
                                                HttpResponse.BodyHandlers.ofString());
        HttpHeaders headers = resp.headers();

        // Single value (first one if repeated)
        System.out.println("Content-Type:   " + headers.firstValue("content-type").orElse("?"));
        // Lookups ignore case
        System.out.println("X-REQUEST-ID:   " + headers.firstValue("X-REQUEST-ID").orElse("?"));
        // Numeric header
        System.out.println("Content-Length: " + headers.firstValueAsLong("Content-Length").orElse(-1));
        // Missing header
        System.out.println("ETag present:   " + headers.firstValue("ETag").isPresent());
        // All values of a repeated header
        System.out.println("Set-Cookie:");
        headers.allValues("Set-Cookie").forEach(v -> System.out.println("  " + v));

        System.out.println("All headers:");
        headers.map().forEach((name, values) -> System.out.println("  " + name + " = " + values));
        server.stop(0);
    }
}

Output:

Content-Type:   application/json; charset=utf-8
X-REQUEST-ID:   7f3c9a
Content-Length: 11
ETag present:   false
Set-Cookie:
  session=abc123; Path=/; HttpOnly; Secure
  theme=dark; Path=/; Max-Age=31536000
All headers:
  cache-control = [no-store]
  content-length = [11]
  content-type = [application/json; charset=utf-8]
  date = [Sat, 17 Oct 2026 19:02:49 GMT]
  set-cookie = [session=abc123; Path=/; HttpOnly; Secure, theme=dark; Path=/; Max-Age=31536000]
  x-request-id = [7f3c9a]

On the server side, exchange.getResponseHeaders() returns a Headers object with set() (replace) and add() (append). You must change headers before calling sendResponseHeaders(), because that call writes the status line and headers to the socket. It also adds Content-length and Date for you.

Use allValues("Set-Cookie") for cookies. Never join Set-Cookie values with commas: the Expires attribute has a comma in it (Expires=Thu, 01 Oct 2026 ...), so the joined string can't be split reliably.

Conditional requests with ETag and Last-Modified

Caching headers let a client skip downloading content it already has. The server sends a validator, either an ETag (an opaque, quoted version string) or Last-Modified (a date). The client sends it back in If-None-Match or If-Modified-Since. If nothing changed, the server responds 304 Not Modified with no body.

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HexFormat;
import java.util.Locale;

public class ConditionalGet {
    static final byte[] CONTENT = "Hello, cached world!".getBytes(StandardCharsets.UTF_8);
    // IMF-fixdate from RFC 9110: always two-digit day, always GMT
    static final DateTimeFormatter HTTP_DATE =
        DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US).withZone(ZoneOffset.UTC);
    static final ZonedDateTime MODIFIED = ZonedDateTime.of(2026, 10, 1, 12, 0, 0, 0, ZoneOffset.UTC);

    public static void main(String[] args) throws Exception {
        byte[] hash = MessageDigest.getInstance("SHA-256").digest(CONTENT);
        String etag = "\"" + HexFormat.of().formatHex(hash, 0, 8) + "\""; // ETags are quoted
        String lastModified = HTTP_DATE.format(MODIFIED);

        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/doc", exchange -> {
            var h = exchange.getResponseHeaders();
            h.set("ETag", etag);
            h.set("Last-Modified", lastModified);
            h.set("Cache-Control", "max-age=60");
            String ifNoneMatch = exchange.getRequestHeaders().getFirst("If-None-Match");
            if (etag.equals(ifNoneMatch)) {
                exchange.sendResponseHeaders(304, -1); // -1 = no body
            } else {
                h.set("Content-Type", "text/plain; charset=utf-8");
                exchange.sendResponseHeaders(200, CONTENT.length);
                exchange.getResponseBody().write(CONTENT);
            }
            exchange.close();
        });
        server.start();
        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/doc");
        HttpClient client = HttpClient.newHttpClient();

        // First request: full response
        HttpResponse<String> first = client.send(HttpRequest.newBuilder(uri).build(),
                                                 HttpResponse.BodyHandlers.ofString());
        String savedEtag = first.headers().firstValue("ETag").orElseThrow();
        System.out.println(first.statusCode() + " body=\"" + first.body() + "\" etag=" + savedEtag);

        // Parse an HTTP date header into a java.time value
        String lm = first.headers().firstValue("Last-Modified").orElseThrow();
        ZonedDateTime modified = ZonedDateTime.parse(lm, DateTimeFormatter.RFC_1123_DATE_TIME);
        System.out.println("Last-Modified: " + lm);
        System.out.println("Last-Modified parsed: " + modified);

        // Second request: send the ETag back, server answers 304 with no body
        HttpRequest revalidate = HttpRequest.newBuilder(uri)
            .header("If-None-Match", savedEtag)
            .build();
        HttpResponse<String> second = client.send(revalidate, HttpResponse.BodyHandlers.ofString());
        System.out.println(second.statusCode() + " body=\"" + second.body() + "\"");
        server.stop(0);
    }
}

Output:

200 body="Hello, cached world!" etag="7464006affd0103b"
Last-Modified: Thu, 01 Oct 2026 12:00:00 GMT
Last-Modified parsed: 2026-10-01T12:00Z
304 body=""

The date gotcha: HTTP dates must use the IMF-fixdate format from RFC 9110, Thu, 01 Oct 2026 12:00:00 GMT. DateTimeFormatter.RFC_1123_DATE_TIME parses it fine, but when it formats a date it writes a one-digit day (Thu, 1 Oct 2026), which strict clients reject. Use an explicit pattern with Locale.US, as above, so day and month names are never translated.

sendResponseHeaders(304, -1) means "no body". Passing 0 would mean "chunked body of unknown length", which isn't allowed for a 304.

Authorization and content negotiation

Authorization carries credentials. With Basic auth the value is Basic plus base64 of user:password. With tokens it's Bearer <token> (see JWT and OAuth). A server that rejects a request responds 401 with a WWW-Authenticate header that says which scheme it expects.

Accept tells the server which formats the client wants. When a response depends on a request header, the server should name that header in Vary, so caches store a separate copy per value.

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AuthAndNegotiation {
    static void send(HttpExchange ex, int status, String contentType, String body) throws IOException {
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        ex.getResponseHeaders().set("Content-Type", contentType + "; charset=utf-8");
        ex.sendResponseHeaders(status, bytes.length);
        ex.getResponseBody().write(bytes);
        ex.close();
    }

    static String basicAuth(String user, String password) {
        String token = user + ":" + password;
        return "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) throws Exception {
        String expected = basicAuth("alice", "s3cret");

        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/user", ex -> {
            String auth = ex.getRequestHeaders().getFirst("Authorization");
            if (!expected.equals(auth)) {
                ex.getResponseHeaders().set("WWW-Authenticate", "Basic realm=\"demo\"");
                send(ex, 401, "text/plain", "unauthorized");
                return;
            }
            // The response depends on Accept, so caches must key on it too
            ex.getResponseHeaders().set("Vary", "Accept");
            String accept = ex.getRequestHeaders().getFirst("Accept");
            if (accept != null && accept.contains("application/json")) {
                send(ex, 200, "application/json", "{\"name\":\"alice\"}");
            } else {
                send(ex, 200, "text/plain", "name=alice");
            }
        });
        server.start();
        URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/user");
        HttpClient client = HttpClient.newHttpClient();

        HttpResponse<String> r1 = client.send(HttpRequest.newBuilder(uri).build(),
                                              HttpResponse.BodyHandlers.ofString());
        System.out.println(r1.statusCode() + " WWW-Authenticate: "
            + r1.headers().firstValue("WWW-Authenticate").orElse(""));

        for (String accept : new String[] {"application/json", "text/plain"}) {
            HttpRequest req = HttpRequest.newBuilder(uri)
                .header("Authorization", basicAuth("alice", "s3cret"))
                .header("Accept", accept)
                .build();
            HttpResponse<String> r = client.send(req, HttpResponse.BodyHandlers.ofString());
            System.out.println(r.statusCode() + " " + r.headers().firstValue("Content-Type").orElse("")
                + " -> " + r.body());
        }
        server.stop(0);
    }
}

Output:

401 WWW-Authenticate: Basic realm="demo"
200 application/json; charset=utf-8 -> {"name":"alice"}
200 text/plain; charset=utf-8 -> name=alice

Basic auth only base64-encodes the password, so use it over HTTPS only. In real code, compare secrets with MessageDigest.isEqual(a, b) rather than String.equals(), so the comparison takes the same time no matter where the strings differ. The accept.contains(...) check is a simplification: a full Accept parser also handles wildcards (*/*, text/*) and quality values (application/json;q=0.9). Frameworks such as Spring MVC and Jakarta REST do this for you.

HttpClient can also answer 401 challenges by itself if you give it an Authenticator: HttpClient.newBuilder().authenticator(...). Setting the Authorization header yourself is simpler and avoids the extra round trip.

Parsing header values

Many headers have structure: a main value followed by ; key=value parameters. Here's a small parser for Content-Type, plus java.net.HttpCookie.parse() for Set-Cookie. The example also shows HttpHeaders.of(map, filter), which builds an immutable HttpHeaders (useful in tests) and drops entries the filter rejects:

import java.net.HttpCookie;
import java.net.http.HttpHeaders;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ParseHeaders {
    record MediaType(String type, Map<String, String> params) {
        // "text/html; charset=ISO-8859-1" -> type + parameters
        static MediaType parse(String header) {
            String[] parts = header.split(";");
            Map<String, String> params = new LinkedHashMap<>();
            for (int i = 1; i < parts.length; i++) {
                String[] kv = parts[i].trim().split("=", 2);
                if (kv.length == 2) {
                    params.put(kv[0].trim().toLowerCase(), kv[1].trim().replace("\"", ""));
                }
            }
            return new MediaType(parts[0].trim().toLowerCase(), params);
        }

        Charset charset(Charset fallback) {
            String cs = params.get("charset");
            return cs == null ? fallback : Charset.forName(cs);
        }
    }

    public static void main(String[] args) {
        // HttpHeaders.of builds an immutable header set; the filter decides what to keep
        HttpHeaders headers = HttpHeaders.of(Map.of(
                "Content-Type", List.of("text/HTML; Charset=\"ISO-8859-1\""),
                "Set-Cookie", List.of(
                    "session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly",
                    "lang=pl; Path=/docs"),
                "X-Internal-Debug", List.of("node-7")),
            (name, value) -> !name.toLowerCase().startsWith("x-internal-"));

        System.out.println("Kept: " + headers.map().keySet());

        MediaType mt = MediaType.parse(headers.firstValue("Content-Type").orElseThrow());
        System.out.println("Type: " + mt.type() + ", charset: " + mt.charset(Charset.forName("UTF-8")));

        for (String raw : headers.allValues("Set-Cookie")) {
            for (HttpCookie c : HttpCookie.parse(raw)) {
                System.out.printf("Cookie %s=%s path=%s maxAge=%d secure=%b httpOnly=%b%n",
                    c.getName(), c.getValue(), c.getPath(), c.getMaxAge(), c.getSecure(), c.isHttpOnly());
            }
        }
    }
}

Output:

Kept: [Content-Type, Set-Cookie]
Type: text/html, charset: ISO-8859-1
Cookie session=abc123 path=/ maxAge=3600 secure=true httpOnly=true
Cookie lang=pl path=/docs maxAge=-1 secure=false httpOnly=false

Type, subtype and parameter names in Content-Type are case-insensitive, so the parser lowercases them. The parameter value is quoted here, which is legal. The parser is deliberately simple: it would break on a quoted value that contains ;. For production code use a library parser, such as Spring's MediaType.parseMediaType() or OkHttp's MediaType.

Cookies with CookieManager

You can read Set-Cookie and write Cookie headers by hand, but it's easier to give the client a CookieHandler. It stores cookies from responses and sends the matching ones (by domain, path, Secure flag and expiry) with later requests:

import com.sun.net.httpserver.HttpServer;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class CookieClient {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/", ex -> {
            if (ex.getRequestURI().getPath().equals("/login")) {
                ex.getResponseHeaders().add("Set-Cookie", "session=xyz789; Path=/; HttpOnly");
            }
            String cookie = ex.getRequestHeaders().getFirst("Cookie");
            byte[] body = ("server saw Cookie: " + cookie).getBytes(StandardCharsets.UTF_8);
            ex.sendResponseHeaders(200, body.length);
            ex.getResponseBody().write(body);
            ex.close();
        });
        server.start();
        String base = "http://localhost:" + server.getAddress().getPort();

        CookieManager cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
        HttpClient client = HttpClient.newBuilder().cookieHandler(cookies).build();

        for (String path : new String[] {"/login", "/me"}) {
            HttpRequest req = HttpRequest.newBuilder(URI.create(base + path)).build();
            System.out.println(path + ": " + client.send(req, HttpResponse.BodyHandlers.ofString()).body());
        }
        System.out.println("Stored: " + cookies.getCookieStore().getCookies());
        server.stop(0);
    }
}

Output:

/login: server saw Cookie: null
/me: server saw Cookie: session=xyz789
Stored: [session=xyz789]

Server-side session handling built on cookies is covered in Sessions.

Default headers on every request

Unlike OkHttp interceptors or Spring's RestClient.Builder.defaultHeader(), HttpClient has no setting for headers that go on every request. The usual pattern is a factory method that returns a pre-filled builder. Since Java 16, HttpRequest.newBuilder(request, filter) copies an existing request and keeps only the headers the filter accepts. Use it to strip credentials before sending a request to a different host:

import java.net.URI;
import java.net.http.HttpRequest;
import java.util.Map;
import java.util.UUID;

public class DefaultHeaders {
    static final Map<String, String> DEFAULTS = Map.of(
        "User-Agent", "inventory-service/2.1",
        "Accept", "application/json");

    // HttpClient has no "default headers" setting, so start every request from a helper
    static HttpRequest.Builder request(String url) {
        HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url));
        DEFAULTS.forEach(b::setHeader);
        return b.setHeader("X-Request-Id", UUID.randomUUID().toString());
    }

    public static void main(String[] args) {
        HttpRequest original = request("https://api.example.com/items")
            .header("Authorization", "Bearer eyJhbGciOi...")
            .setHeader("Accept", "text/csv") // override a default
            .build();
        print("original", original);

        // Java 16+: copy a request, keeping only the headers the filter accepts
        HttpRequest forwarded = HttpRequest.newBuilder(original,
                (name, value) -> !name.equalsIgnoreCase("Authorization"))
            .uri(URI.create("https://mirror.example.net/items"))
            .build();
        print("forwarded", forwarded);
    }

    static void print(String label, HttpRequest r) {
        System.out.println(label + " " + r.uri());
        r.headers().map().forEach((k, v) ->
            System.out.println("  " + k + ": " + (k.equals("X-Request-Id") ? "<uuid>" : v)));
    }
}

Output:

original https://api.example.com/items
  Accept: [text/csv]
  Authorization: [Bearer eyJhbGciOi...]
  User-Agent: [inventory-service/2.1]
  X-Request-Id: <uuid>
forwarded https://mirror.example.net/items
  Accept: [text/csv]
  User-Agent: [inventory-service/2.1]
  X-Request-Id: <uuid>

A per-request ID such as X-Request-Id helps when you trace one call through the logs of several services. Custom headers no longer need the X- prefix (RFC 6648 deprecated it), but many APIs still use it.

Response headers in every reply and HttpURLConnection

On the server, headers that belong on every response, such as security headers, are best added in one place. With HttpServer that place is a Filter. In Spring it's a OncePerRequestFilter or Spring Security's headers() configuration. The example reads the response with the legacy HttpURLConnection, which you'll still meet in older code:

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class SecurityHeaders {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        HttpContext ctx = server.createContext("/", ex -> {
            byte[] body = "<h1>hi</h1>".getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
            ex.sendResponseHeaders(200, body.length);
            ex.getResponseBody().write(body);
            ex.close();
        });
        // A filter runs before the handler, so every response gets these headers
        ctx.getFilters().add(Filter.beforeHandler("security headers", ex -> {
            var h = ex.getResponseHeaders();
            h.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains");
            h.set("X-Content-Type-Options", "nosniff");
            h.set("Content-Security-Policy", "default-src 'self'");
            h.set("Referrer-Policy", "strict-origin-when-cross-origin");
        }));
        server.start();

        // The older HttpURLConnection API
        var url = URI.create("http://localhost:" + server.getAddress().getPort() + "/").toURL();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Accept", "text/html");      // replaces
        conn.addRequestProperty("Accept-Encoding", "identity"); // appends
        System.out.println("Status: " + conn.getResponseCode());
        System.out.println("Content-Type: " + conn.getContentType());
        System.out.println("CSP: " + conn.getHeaderField("content-security-policy"));

        Map<String, List<String>> fields = conn.getHeaderFields();
        System.out.println("null key: " + fields.get(null)); // the status line
        fields.keySet().stream()
            .filter(k -> k != null)
            .sorted()
            .forEach(k -> System.out.println("  " + k));
        conn.disconnect();
        server.stop(0);
    }
}

Output:

Status: 200
Content-Type: text/html; charset=utf-8
CSP: default-src 'self'
null key: [HTTP/1.1 200 OK]
  Content-length
  Content-security-policy
  Content-type
  Date
  Referrer-policy
  Strict-transport-security
  X-content-type-options

HttpURLConnection quirks to know about:

What these security headers do:

Header Purpose
Strict-Transport-Security Browser uses HTTPS only for this host for the given number of seconds
X-Content-Type-Options: nosniff Browser trusts Content-Type instead of guessing the type from the content
Content-Security-Policy Limits where scripts, styles and images may load from, which reduces the damage from XSS
Referrer-Policy Controls how much of the URL is sent in Referer to other sites

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents