Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To add custom headers in a Java WebSocket client, add them to the HTTP request that performs the opening WebSocket handshake. The exact code depends on the client library: Jakarta WebSocket uses beforeRequest, the JDK client uses WebSocket.Builder.header, and Jetty, OkHttp, and Java-WebSocket provide their own request APIs.

Headers added after the connection is established cannot change the original upgrade request. WebSocket messages are frames rather than HTTP requests, so authentication or tracing information sent later must use the application protocol or a new connection.

Key takeaways

  • Custom headers belong on the opening HTTP upgrade request, not on later calls such as sendText.
  • Jakarta WebSocket / JSR 356 uses ClientEndpointConfig.Configurator.beforeRequest(Map<String, List<String>>) to modify handshake headers.
  • The JDK WebSocket client uses WebSocket.Builder.header(name, value), but WebSocket protocol headers such as Upgrade and Sec-WebSocket-Key are not caller-defined headers.
  • Jetty uses ClientUpgradeRequest, OkHttp uses an HTTP Request, and Java-WebSocket uses a header map or addHeader.
  • A header added to an already-open WebSocket has no effect on the original handshake; token rotation therefore requires application-level handling or reconnection.
  • If a header is present in client code but missing at the server, inspect proxies, gateways, redirects, reconnect code, and the actual wire-level handshake.

What does a custom WebSocket header belong to?

A custom WebSocket header belongs to the initial HTTP upgrade request. Before a WebSocket session exists, the client sends an HTTP request similar to this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
GET /socket HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: generated-by-client
Sec-WebSocket-Version: 13
Authorization: Bearer eyJ...
X-Tenant-ID: tenant-123

Authorization and X-Tenant-ID are ordinary application-defined HTTP headers in that request. The client library generates the WebSocket negotiation fields and uses the HTTP response to decide whether the upgrade succeeds.

#1 Best Overall
Sale
UGREEN Cat 8 Ethernet Cable 6FT, High Speed Braided 40Gbps 2000Mhz Network Cord Cat8 RJ45 Shielded Indoor Heavy Duty LAN Cables Compatible with Gaming PC PS5 PS4 PS3 Xbox Modem Router 6FT
  • 40 Gbps 2000 Mhz High Speed: The Cat 8 ethernet cable support max. 40 Gbps data transfer and 2000 MHz Brandwith, ideal for gaming and streaming, greatly improving upload and download speed, sound, image and resolution quality
  • Excellent Anti-interference: The ethernet cable comes with 4 shielded foiled twisted pairs (F/FTP), pure copper core and gold-plated RJ45 connector, reducing interference, noise and crosstalk, making network speed faster and more stable
  • Marvelous Durability: Internet cable wrapped with quality cotton braided cord, which makes the LAN cable stronger and more durable. The test proves that this internet cable can be bent at least 10000 times without broken, very suitable for long-term use
  • PoE Supported: All lengths of ethernet cord can support the PoE power supply function except 65ft. You don't need additional power supply when installing a PoE camera, which is very convenient and safe
  • Wide Compatibility: With the RJ45 Connector, network cable can be perfectly compatible with computers, laptops, modems, routers, PS5, X-Box and other networking devices. It can also be fully backward compatible with Cat7, Cat6e, Cat6, Cat5e, Cat5

A WebSocket message sent after the upgrade is not another HTTP request. A call such as sendText(...) sends a WebSocket data frame and cannot add an HTTP header to the completed handshake. If the server expects authentication in the first message instead, follow that server’s application protocol; first-message authentication is not the same as authenticating the HTTP upgrade.

Which Java WebSocket client are you using?

There is no single universal Java WebSocket header API. Choose the row that matches the library creating your connection.

Client Header mechanism Use when
Jakarta WebSocket / JSR 356 ClientEndpointConfig.Configurator.beforeRequest(...) The application uses a Jakarta EE, Java EE, or compatible WebSocket container.
JDK java.net.http.WebSocket WebSocket.Builder.header(name, value) The application wants the JDK client without a third-party WebSocket dependency.
Eclipse Jetty ClientUpgradeRequest.setHeader(...) The application already uses Jetty or needs Jetty-specific upgrade customization.
OkHttp Request.Builder.header(...) or addHeader(...) The application already uses OkHttp’s HTTP request model.
Java-WebSocket A constructor header map or addHeader(...) A lightweight, library-specific WebSocket client is appropriate.

How do you add headers with Jakarta WebSocket or JSR 356?

Jakarta WebSocket adds handshake headers by subclassing ClientEndpointConfig.Configurator and overriding beforeRequest. The WebSocket implementation calls beforeRequest after formulating the request and immediately before sending the handshake. The supplied map is mutable, as described in the ClientEndpointConfig.Configurator API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import jakarta.websocket.ClientEndpointConfig;

import java.util.List;
import java.util.Map;

public final class AuthConfigurator
        extends ClientEndpointConfig.Configurator {

    private final String token;

    public AuthConfigurator(String token) {
        this.token = token;
    }

    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
        headers.put("Authorization",
                List.of("Bearer " + token));
        headers.put("X-Tenant-ID",
                List.of("tenant-123"));
    }
}

Attach the configurator to a client endpoint configuration and pass that configuration to connectToServer:

import jakarta.websocket.ClientEndpointConfig;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;

import java.net.URI;

ClientEndpointConfig config =
        ClientEndpointConfig.Builder.create()
                .configurator(new AuthConfigurator(token))
                .build();

WebSocketContainer container =
        ContainerProvider.getWebSocketContainer();

Session session = container.connectToServer(
        endpoint,
        config,
        URI.create("wss://example.com/socket"));

In this example, endpoint is the application endpoint instance or endpoint object used by the WebSocket implementation. The important ordering is that the configurator is attached before connectToServer creates the handshake.

Should you import javax.websocket or jakarta.websocket?

Use the namespace supplied by the WebSocket implementation and dependency used by the application. Older Java EE applications may use javax.websocket, while Jakarta applications use jakarta.websocket. The customization mechanism is the same, but the namespaces are not interchangeable. The current Jakarta WebSocket API documentation shows the Jakarta namespace, while the older Java EE API documentation shows javax.websocket.

How do you send multiple values for one header?

The Jakarta WebSocket callback receives a Map<String, List<String>>, so a list represents the values for a header. Use a one-element list for a normal single-value header:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
headers.put("X-Feature", List.of("one"));

Use multiple list elements only when the protocol intentionally requires multiple values:

headers.put("X-Feature", List.of("one", "two"));

Use put when the application needs one definitive value. Use computeIfAbsent(...).add(...) only when appending another value is deliberate:

headers.computeIfAbsent(
        "X-Trace-ID",
        ignored -> new java.util.ArrayList<>())
       .add(traceId);

What is afterResponse used for?

afterResponse(HandshakeResponse) is for inspecting the handshake response after the server replies. It is useful for diagnostics, such as examining response headers or understanding a failed upgrade, but it is not a place to add request headers because the request has already been sent.

Rank #2
DbillionDa Cat 8 Ethernet Cable, 6FT 40Gbps 2000MHz RJ45 LAN Cable
  • Designed for Outdoor & Direct Burial Installations – Heavy-duty double-shielded Cat8 Ethernet cable minimizes EMI/RFI interference and delivers stable long-distance performance. Waterproof, anti-corrosion PVC jacket allows safe direct burial and reliable use in outdoor or indoor environments.
  • 26AWG for Stable High-Load Networks – Thicker 26AWG conductors provide faster, more stable data transmission than standard 32AWG cables. Ideal for high-performance home networks, gaming setups, smart homes, and data-intensive applications.
  • F/FTP Shielding & Hyper-Speed Performance: Cat8 Ethernet cable constructed with 4 shielded foiled twisted pairs and 26AWG OFC conductors; supports bandwidth up to 2000 MHz and data transmission speeds up to 40 Gbps, effectively reducing signal interference and ensuring stable connections. Ideal for low-latency gaming, 4K/8K streaming, and high-speed internet connections.
  • RJ45 Connectors & Wide Compatibility: Cat8 Ethernet cable with two shielded RJ45 connectors; compatible with networking switches, IP cameras, routers, Nintendo Switch, modems, PS3, PS4, Xbox, patch panels, servers, smart TVs, and more; works with Cat7, Cat6, Cat5e, and Cat5 devices
  • Weatherproof & UV Resistant: Outdoor-rated Cat8 Ethernet cable with UV-resistant PVC jacket; withstands direct sunlight, extreme cold, humidity, and hot weather; anti-aging and durable; Includes 18-month support.

How do you add headers with the JDK WebSocket client?

The JDK java.net.http.WebSocket client adds ordinary handshake headers through WebSocket.Builder.header(name, value) before buildAsync. The JDK WebSocket.Builder documentation states that WebSocket protocol headers are illegal through this method.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;

HttpClient httpClient = HttpClient.newHttpClient();

WebSocket webSocket = httpClient.newWebSocketBuilder()
        .header("Authorization", "Bearer " + token)
        .header("X-Tenant-ID", "tenant-123")
        .subprotocols("chat")
        .buildAsync(
                URI.create("wss://example.com/socket"),
                new WebSocket.Listener() {
                    @Override
                    public CompletionStage<?> onText(
                            WebSocket webSocket,
                            CharSequence data,
                            boolean last) {
                        System.out.println(data);
                        return WebSocket.Listener.super
                                .onText(webSocket, data, last);
                    }
                })
        .join();

The .header(...) calls affect the opening handshake because they occur before buildAsync. The returned CompletionStage completes when the asynchronous connection succeeds or fails; calling join() makes this example wait for the result.

Which JDK WebSocket headers must you avoid?

Do not try to set or replace headers controlled by the WebSocket implementation:

Upgrade

Header or category Correct approach
Authorization Add it with the client header API when the server expects it.
X-API-Key Add it as an application-defined header.
Cookie Use cookie support when available, or provide a valid cookie header.
Origin Set it only when the server’s origin policy requires it and the client permits it.
Sec-WebSocket-Protocol Use .subprotocols(...).
Let the WebSocket implementation create it.
Connection Let the WebSocket implementation manage it.
Sec-WebSocket-Key Never set it manually.
Sec-WebSocket-Version Never set it manually.
Sec-WebSocket-Extensions Use the library’s extension or feature configuration.

The JDK builder may reject prohibited or invalid headers. That restriction prevents an application from constructing an invalid WebSocket handshake; it is not evidence that ordinary application headers are unsupported.

How do you add headers with Eclipse Jetty?

Jetty uses a ClientUpgradeRequest for custom headers, cookies, and subprotocols. Create the request, configure it, and pass the request to the matching WebSocketClient.connect overload. Jetty APIs are version-sensitive, so verify the example against the Jetty WebSocket client documentation for the Jetty major version in your application.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;

import java.net.URI;

WebSocketClient client = new WebSocketClient();
client.start();

ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("Authorization", "Bearer " + token);
request.setHeader("X-Tenant-ID", "tenant-123");
request.setSubProtocols("chat");

client.connect(
        endpoint,
        URI.create("wss://example.com/socket"),
        request);

Jetty also exposes explicit cookie support:

request.getCookies().add(
        new java.net.HttpCookie("session", sessionValue));

Use Jetty’s cookie API when the server expects cookie-based authentication. Use setSubProtocols when the server requires a subprotocol instead of manually writing Sec-WebSocket-Protocol.

How do you add headers with OkHttp?

OkHttp builds the WebSocket handshake from an ordinary HTTP Request. Put the headers on the request before passing that request to OkHttpClient.newWebSocket, as shown in the OkHttpClient API documentation.

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url("wss://example.com/socket")
        .header("Authorization", "Bearer " + token)
        .header("X-Tenant-ID", "tenant-123")
        .build();

WebSocket webSocket =
        client.newWebSocket(request, new WebSocketListener() {
            // callbacks
        });

Use header(name, value) when one value should replace an existing value. Use addHeader(name, value) when multiple header fields are intentionally required. OkHttp rejects configuration that conflicts with the WebSocket protocol instead of allowing an invalid handshake; the OkHttp WebSocket tests demonstrate rejection of forbidden WebSocket headers.

How do you add headers with Java-WebSocket?

Java-WebSocket accepts a header map in the WebSocketClient constructor and also provides methods such as addHeader, removeHeader, and clearHeaders. The library-specific behavior is documented in the WebSocketClient source documentation.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import org.java_websocket.client.WebSocketClient;

import java.net.URI;
import java.util.Map;

Map<String, String> headers = Map.of(
        "Authorization", "Bearer " + token,
        "X-Tenant-ID", "tenant-123");

WebSocketClient client =
        new WebSocketClient(
                URI.create("wss://example.com/socket"),
                headers) {
            // implement callbacks
        };

client.connect();

Headers are sent in the handshake. Calling addHeader after the connection has already been established does not modify that connection; apply the header before the next connection or reconnect with the updated headers.

Rank #3
Jadaol Cat6/Cat6A Ethernet Cable 50FT Flat with Clips 10Gbps Network, White
  • Cat 6 performance at a Cat5e price but with higher bandwidth
  • High Performance Cat6, 30 AWG, RJ45 Ethernet Patch Cable provides universal connectivity for LAN network components such as PCs,computer servers,printers,routers,switch boxes,network media players,NAS,VoIP phones
  • Jadaol cat6 standard cable support Cat8 and Cat7 network and provides performance of up to 250 MHz 10Gbps and is suitable for 10BASE-T, 100BASE-TX (Fast Ethernet), 1000BASE-T/1000BASE-TX (Gigabit Ethernet) and 10GBASE-T (10-Gigabit Ethernet)
  • UTP(Unshielded Twisted Pair) patch cable with RJ45 gold-plated Connectors and are made of 100% bare copper wire, ensure minimal noise and interference
  • The unique flat cable shape allows for a cleaner and safer installation. You can easily and seamlessly make the cable run along walls, follow edges & corners or even make it completely invisible by sliding it under a carpet.

Which authentication and metadata mechanism should you use?

The best mechanism is the one required by the server, but the mechanisms have different security and protocol meanings.

Mechanism What it does Main consideration
Authorization header Sends a bearer token or other HTTP authentication value during the handshake. Use wss:// for credentials that must be protected in transit, and do not log the complete token.
API-key header Sends a value such as X-API-Key during the handshake. Keep the key out of source control and inject it through configuration, an environment variable, or a secret manager.
Cookie Uses an existing session or cookie-based authentication scheme. Prefer a library’s cookie API when available, such as Jetty’s cookie support.
Subprotocol Negotiates an application protocol during the WebSocket upgrade. Use the client’s subprotocol method rather than manually setting Sec-WebSocket-Protocol.
Query parameter Places a value in the WebSocket URL. URLs may be logged by proxies, servers, monitoring systems, and diagnostics, so avoid long-lived secrets when possible.
First WebSocket message Sends authentication or setup data after the socket opens. The socket may briefly be unauthenticated, and the server may reject or close it before authentication succeeds.

Should you use an Authorization header, cookie, or query parameter?

Use the server’s documented handshake authentication mechanism. An Authorization header is often clearer for bearer-token authentication, a cookie is appropriate when the server uses a session cookie, and a query parameter is a compatibility fallback rather than an equivalent security substitute.

A URL such as wss://example.com/socket?token=... can expose a token to access logs, proxy logs, monitoring tools, browser history, or diagnostic output. Query parameters also introduce URL encoding and length concerns. A first-message authentication protocol avoids putting the credential in the URL but does not authenticate the HTTP upgrade itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should you handle token rotation and reconnects?

Headers are created for each opening handshake. Changing a token provider or header map does not update an already-open WebSocket, so reconnect logic must create or configure a new handshake with the current credential.

For Jakarta WebSocket, retrieving the token inside beforeRequest helps avoid reusing a stale value:

@Override
public void beforeRequest(Map<String, List<String>> headers) {
    String currentToken = tokenProvider.currentToken();
    headers.put("Authorization",
            List.of("Bearer " + currentToken));
}

A shared configurator or header map should not be mutated concurrently without an intentional synchronization strategy. Reconnect code should also reapply every required header; a reconnect that creates a new request without copying authentication or tenant headers can fail even when the first connection succeeded.

Why is the server reporting a missing header or returning 401?

A missing header or HTTP 401/403 response usually means the handshake request, authentication format, destination, or infrastructure path does not match the server’s expectations. A WebSocket connection can fail as an ordinary HTTP handshake before a WebSocket session exists.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Confirm timing. Verify that the header is configured before connect, buildAsync, newWebSocket, or the equivalent connection call.
  2. Confirm the phase. Make sure the code modifies the handshake request rather than trying to attach an HTTP header to a later WebSocket message.
  3. Confirm the exact name and format. Check spelling, capitalization where relevant to the server framework, the required authentication scheme, and the required Bearer prefix.
  4. Confirm the endpoint. Check the path, host, virtual host, and tenant value. A valid token sent to the wrong gateway can still produce 401 or 403.
  5. Check server policy. The server may expect a cookie, reject the requested origin, or validate the tenant independently of the token.
  6. Inspect intermediaries. Reverse proxies, gateways, load balancers, and security filters can remove, rewrite, or block custom headers.
  7. Inspect the actual handshake safely. Use a test server, proxy trace, server-side handshake logging, or redacted client logging. Never print complete bearer tokens or API keys.

HTTP 401 commonly indicates an expired, malformed, or incorrectly formatted credential, but it can also result from a gateway authentication rule. HTTP 403 can indicate origin, tenant, authorization, or infrastructure policy. The status alone does not identify which layer rejected the request.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What does “protocol header not permitted” mean?

“Protocol header not permitted” usually means the application attempted to set a header owned by the WebSocket implementation. Remove the manual header and use the client’s dedicated API for subprotocols, extensions, and upgrade negotiation.

For example, use .subprotocols("chat") with the JDK client, request.setSubProtocols("chat") with Jetty, or the preferred-subprotocol configuration in Jakarta WebSocket. Do not manually set Sec-WebSocket-Protocol, Sec-WebSocket-Key, Sec-WebSocket-Version, Upgrade, or Connection.

Rank #4
Cable Matters 10Gbps Snagless Cat 6 Ethernet Cable, 25ft, Black
  • High-Performance Connectivity: This Cat 6 ethernet cable is designed for superior performance, with a 24 AWG copper wire core. It provides universal connectivity as an ethernet cord for LAN network components such as PCs, servers, printers, routers, and more, ensuring reliable and fast network connections
  • Advanced Cat6 Technology: Experience Cat6 performance with higher bandwidth at a Cat5e price. This network cable is future-proof, ready for 10-Gigabit Ethernet and backwards compatible with any existing Cat 5 cable network. It meets or exceeds Category 6 performance according to the TIA/EIA 568-C.2 standard
  • Reliable Wired Network Solution: Known variously as a Cat6 network cable, ethernet cable Cat 6, or Cat 6 data/LAN cable, this RJ45 cable offers a more secure and reliable connection than wireless networks. It's ideal for internet connections that demand consistency and security
  • Durable and Secure Design: The connectors of this ethernet cable feature gold-plated contacts and strain-relief boots for enhanced durability. Bare copper conductors not only improve cable performance but also comply with communication cable specifications
  • High-Speed Data Transfer: With up to 550 MHz bandwidth, this ethernet cord is ideal for server applications, cloud computing, video surveillance, and streaming high-definition video. It also supports Power over Ethernet (PoE, PoE+, PoE++) for powering devices like IP cameras, VoIP phones, and wireless access points, ensuring fast and reliable network performance.

Why does a header appear in code but disappear on the wire?

A header that appears in source code but not in the received handshake may have been added at the wrong time, attached to an unused request object, removed during a reconnect, rejected by the client, or stripped by an intermediary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The header was added after the WebSocket connection was established.
  • The code configured one request object but passed a different request to the WebSocket factory.
  • A reconnect path rebuilt the request without the original headers.
  • The client library replaced or rejected a prohibited header.
  • A proxy, gateway, load balancer, or security filter removed or rewrote the header.
  • The server logs only selected headers or combines repeated values differently.
  • A redirect caused a new handshake request to a different destination.

Authenticated WebSocket endpoints should avoid redirects where possible. Sensitive headers should not automatically be forwarded to a different host or trust boundary. If redirects are unavoidable, validate the final destination before forwarding credentials.

How should you troubleshoot a proxy or load balancer?

Trace the request through each layer instead of assuming that a successful TCP or TLS connection proves that the authenticated WebSocket upgrade succeeded.

  1. Log only safe client-side facts, such as whether the authorization header was present and a redacted token identifier.
  2. Check that the reverse proxy is configured to pass WebSocket upgrades and the required application headers.
  3. Check gateway authentication rules separately from application authentication rules.
  4. Review load-balancer and reverse-proxy access logs for the handshake path and response status.
  5. Compare server-side handshake headers with the headers the client intended to send.
  6. Test the endpoint without an intermediary when that is safe and possible.

When the header exists in a direct test but disappears only behind the gateway, the client code is not the first place to change. Investigate intermediary policy, header allowlists, routing, redirects, and authentication termination.

Security checklist for custom WebSocket headers

  • Prefer wss:// when sending credentials or other sensitive values.
  • Do not log complete bearer tokens, API keys, cookies, or credential-bearing URLs.
  • Keep API keys and tokens out of source control; inject them through protected configuration.
  • Do not put long-lived credentials in query parameters unless the server requires that design and the exposure is understood.
  • Use least-privileged credentials with an appropriate lifetime.
  • Refresh expiring credentials before reconnecting and rebuild the handshake with the current value.
  • Validate redirect destinations before forwarding sensitive headers.
  • Do not concatenate untrusted input into arbitrary header syntax, and reject raw line breaks in header values.
  • Do not override protocol-controlled headers.
  • Confirm that proxies and gateways preserve the headers the server is designed to receive.

Which client should you choose?

Choose Jakarta WebSocket when portability within a managed Jakarta EE or Java EE environment matters. Choose the JDK client when a third-party dependency is undesirable and ordinary handshake headers are sufficient. Choose Jetty for Jetty integration and detailed upgrade customization, OkHttp when the application already uses OkHttp’s request model, and Java-WebSocket when a lightweight dedicated client with a simple header map fits the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Requirement Most suitable route Trade-off
Portable container API Jakarta WebSocket / JSR 356 The configurator pattern is less obvious, and javax/jakarta mismatches are common.
No third-party WebSocket dependency JDK java.net.http.WebSocket The API is asynchronous and restricts protocol-controlled headers.
Jetty-specific cookies, listeners, or proxy integration Jetty Code is less portable and must track the Jetty API version.
One request model for HTTP and WebSocket OkHttp OkHttp intentionally limits invalid or protocol-conflicting customization.
Simple dedicated client and header map Java-WebSocket The API and lifecycle are specific to that third-party library.

The practical rule is simple: identify the library that creates the socket, configure the library’s opening request before connecting, and let the library own WebSocket negotiation headers.

Frequently Asked Questions

Can I add an HTTP header after a Java WebSocket connection is open?

No. HTTP headers belong to the opening upgrade request, which has already completed when the WebSocket is open. Send later data through the application protocol or reconnect with a newly configured handshake.

Why does the Java WebSocket server return 401 even though the Authorization header is in my code?

A 401 can result from an expired or malformed token, a missing Bearer scheme, a server expecting a cookie, a proxy stripping the header, an incorrect endpoint, or a gateway authentication rule. Inspect the actual handshake with secrets redacted.

Can I manually set Sec-WebSocket-Protocol in Java?

Use the WebSocket client’s subprotocol API instead of manually setting Sec-WebSocket-Protocol. The JDK client provides subprotocols(…), Jetty provides setSubProtocols(…), and Jakarta WebSocket provides preferred-subprotocol configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I put a WebSocket token in the URL query string?

Use a query parameter only when the server requires that compatibility pattern and the exposure is acceptable. URLs may be recorded by proxies, servers, monitoring tools, browser history, and diagnostics, so a header or cookie is generally preferable for sensitive credentials.

The Bottom Line

Custom headers in a Java WebSocket client must be configured before the opening handshake. Use beforeRequest for Jakarta WebSocket, WebSocket.Builder.header for the JDK client, ClientUpgradeRequest for Jetty, an OkHttp Request for OkHttp, or the header map and mutation methods provided by Java-WebSocket. Never replace protocol-managed headers, and investigate proxies and reconnect paths when a correctly configured header does not reach the server.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.