如何在 Java Websocket 客户端中添加标头

2022-09-04 01:31:58

我正在使用类连接到Java中的websocket服务器。javax.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标头

这可能吗?

我知道这在服务器端是可能的。客户端是否有类似的解决方案?ServerEndpointConfig.Configurator.modifyHandshake


答案 1

ClientEndpointConfig.Configurator.beforeRequest(Map<String,List<String>> headers)可能可用。

关于这个论点的JavaDoc是这样说的:headers

实现即将发送的握手请求标头的可变映射以启动握手交互。

那么,为什么不覆盖下面这样的方法呢?beforeRequest

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

您可以传递到 。ClientEndpointConfigconnectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path)


答案 2
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);
    }
}

推荐