How to add headers in Java Websocket client
Asked Answered
G

5

14

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?

Gambol answered 29/6, 2015 at 12:2 Comment(0)
M
15

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

Musketry answered 30/6, 2015 at 5:20 Comment(0)
P
5
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);
    }
}
Popular answered 10/10, 2017 at 18:5 Comment(0)
B
2
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));
Bors answered 14/2, 2020 at 16:17 Comment(0)
P
1

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

}
Pasadena answered 21/5, 2020 at 3:13 Comment(0)
S
0

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.

Specialist answered 3/2, 2022 at 15:6 Comment(1)
Please don't ask a question under the answer of another question.Espinal

© 2022 - 2024 — McMap. All rights reserved.