Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
kavai77 Avatar asked Jun 29 '15 12:06

kavai77


1 Answers

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).

like image 120
Takahiko Kawasaki Avatar answered Oct 05 '22 05:10

Takahiko Kawasaki