javawebsocketjava-websocket

How to add headers in Java Websocket client


I am connecting to a websocket server in Java using javax.websocket classes.

import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;

public class WSClient {
    private WebSocketContainer webSocketContainer;

    public void sendMessage(URI endpointURI, String message) throws IOException, DeploymentException {
        Session session = webSocketContainer.connectToServer(MyClientEndpoint.class, endpointURI);
        session.getAsyncRemote().sendText(message);
    }
}

For the initial HTTP handshake I want to add extra HTTP Headers to the request on the Client side

Is this possible?

I know that this is possible on server side using ServerEndpointConfig.Configurator.modifyHandshake. Is there a similar solution on client side?


Solution

  • ClientEndpointConfig.Configurator.beforeRequest(Map<String,List<String>> headers) may be usable.

    The JavaDoc about the argument headers says as follows:

    the mutable map of handshake request headers the implementation is about to send to start the handshake interaction.

    So, why don't you override beforeRequest method like below?

    @Override
    public void beforeRequest(Map<String,List<String>> headers)
    {
        List<String> values = new ArrayList<String>();
        values.add("My Value");
    
        headers.put("X-My-Custom-Header", values);
    }
    

    You can pass ClientEndpointConfig to connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path).