kavai77
kavai77

Reputation: 6616

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?

Upvotes: 14

Views: 19024

Answers (5)

Sankar Ganesh
Sankar Ganesh

Reputation: 11

I tried the similar code as below

webSocketContainer.connectToServer(MyClientEndpoint.class, clientConfig, new URI(uri));

Here 'MyClientEndpoint' extends Endpoint (it should as per the method specification). But there is no @OnMessage event listener available in Endpoint class.. If I simply use webSocketContainer.connectToServer(this, new URI(uri));, without client configuration, I'm getting authorization issue. Kindly advise.

Upvotes: 0

Tonecops
Tonecops

Reputation: 167

Update 2020. This is how IntelliJ community proposed it:

  public WsClient(String uri) throws Exception {

    ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create();

    configBuilder.configurator(new ClientEndpointConfig.Configurator() {
        public void beforeRequest(Map<String, List<String>> headers) {
            headers.put("FriendlyName", Arrays.asList("TakaTurautin"));
        }
    });
    ClientEndpointConfig clientConfig = configBuilder.build();
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    container.connectToServer(this, clientConfig, URI.create(uri));

}

Upvotes: 1

tissa
tissa

Reputation: 396

Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
    headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID));
    }
});
ClientEndpointConfig clientConfig = configBuilder.build();
webSocketContainer.connectToServer(MyClientEndpoint.class, clientConfig, new URI(uri));

Upvotes: 2

sky54521
sky54521

Reputation: 61

public class Config extends ClientEndpointConfig.Configurator{
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
        headers.put("Pragma", Arrays.asList("no-cache"));
        headers.put("Origin", Arrays.asList("https://www.bcex.ca"));
        headers.put("Accept-Encoding", Arrays.asList("gzip, deflate, br"));
        headers.put("Accept-Language", Arrays.asList("en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4"));
        headers.put("User-Agent", Arrays.asList("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"));
        headers.put("Upgrade", Arrays.asList("websocket"));
        headers.put("Cache-Control", Arrays.asList("no-cache"));
        headers.put("Connection", Arrays.asList("Upgrade"));
        headers.put("Sec-WebSocket-Version", Arrays.asList("13"));
    }

    @Override
    public void afterResponse(HandshakeResponse hr) {
        Map<String, List<String>> headers = hr.getHeaders();
        log.info("headers -> "+headers);
    }
}

Upvotes: 5

Takahiko Kawasaki
Takahiko Kawasaki

Reputation: 19001

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

Upvotes: 15

Related Questions