How to add headers to Java Websocket client

I connect to the websocket server in Java using the 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 additional HTTP headers to the client side request

Is it possible?

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

+6
source share
2 answers

ClientEndpointConfig . Configurator . beforeRequest (Map<String,List<String>> headers ) ClientEndpointConfig . Configurator . beforeRequest (Map<String,List<String>> headers ) can be used.

The JavaDoc on the headers argument says the following:

a map of variable headers for handshake requests that are about to be sent to start shaking hands.

So, why don't you override the beforeRequest method as shown 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 ClientEndpointConfig connectToServer (Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path) .

+8
source
 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); } } 
0
source

Source: https://habr.com/ru/post/989943/


All Articles