如何在 Java Websocket 客户端中添加 headers

How to add headers in Java Websocket client

我正在使用 javax.websocket 类.

连接到 Java 中的 websocket 服务器
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);
    }
}

对于初始 HTTP 握手,我想在 客户端 [= 的请求中添加额外的 HTTP Headers 15=]

这可能吗?

我知道这可以在服务器端使用 ServerEndpointConfig.Configurator.modifyHandshake。客户端有没有类似的解决方案?

<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.html">ClientEndpointConfig</a>.<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.Configurator.html">Configurator</a>.<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.Configurator.html#beforeRequest(java.util.Map)">beforeRequest</a>(Map<String,List<String>> <b>headers</b>) 可能可用。

关于参数 <b>headers</b> 的 JavaDoc 说如下:

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

那么,为什么不重写 <b><a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.Configurator.html#beforeRequest(java.util.Map)">beforeRequest</a></b> 方法,如下所示?

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

可以通过<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.html">ClientEndpointConfig</a> to <a href="http://docs.oracle.com/javaee/7/api/javax/websocket/WebSocketContainer.html#connectToServer(java.lang.Class,%20javax.websocket.ClientEndpointConfig,%20java.net.URI)">connectToServer</a>(Class<? extends Endpoint> endpointClass, <a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.html">ClientEndpointConfig</a>cec,URI路径).

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

2020 年更新。IntelliJ 社区是这样提议的:

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

}

我试过类似下面的代码

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

这里 'MyClientEndpoint' 扩展端点(它应该按照方法规范)。 但是端点 class 中没有可用的 @OnMessage 事件侦听器。如果我只是使用 webSocketContainer.connectToServer(this, new URI(uri));,没有客户端配置,我会遇到授权问题。请指教。