gpt4 book ai didi

java - 如何在 Java Websocket 客户端中添加 header

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:54:48 46 4
gpt4 key购买 nike

我正在使用 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 header

这可能吗?

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

最佳答案

<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.html" rel="noreferrer noopener nofollow">ClientEndpointConfig</a>.<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.Configurator.html" rel="noreferrer noopener nofollow">Configurator</a>.<a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.Configurator.html#beforeRequest(java.util.Map)" rel="noreferrer noopener nofollow">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)" rel="noreferrer noopener nofollow">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" rel="noreferrer noopener nofollow">ClientEndpointConfig</a><a href="http://docs.oracle.com/javaee/7/api/javax/websocket/WebSocketContainer.html#connectToServer(java.lang.Class,%20javax.websocket.ClientEndpointConfig,%20java.net.URI)" rel="noreferrer noopener nofollow">connectToServer</a>(Class<? extends Endpoint> endpointClass, <a href="http://docs.oracle.com/javaee/7/api/javax/websocket/ClientEndpointConfig.html" rel="noreferrer noopener nofollow">ClientEndpointConfig</a> cec, URI path) .

关于java - 如何在 Java Websocket 客户端中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31115205/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com