我使用Tyrus客户端软件包从我的Java应用程序中使用了一个websocket端点,该端点在初始客户端请求中需要cookie头。浏览Tyrus客户端API文档和谷歌并没有让我走得太远。任何想法如何做到这一点?
答案 0 :(得分:3)
找到了我自己的问题的解决方案,所以我想分享。解决方案是在ClientEndpointConfig上设置自定义配置程序,并覆盖该配置程序中的beforeRequest方法以添加cookie标头。
例如:
ClientEndpointConfig cec = ClientEndpointConfig.Builder.create()
.configurator(new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest(Map<String, List<String>> headers) {
super.beforeRequest(headers);
List<String> cookieList = headers.get("Cookie");
if (null == cookieList) {
cookieList = new ArrayList<>();
}
cookieList.add("foo=\"bar\""); // set your cookie value here
headers.put("Cookie", cookieList);
}
}).build();
然后在随后的ClientEndpointConfig
或ClientManager.connectToServer
来电中使用此ClientManager.asyncConnectToServer
个对象。
答案 1 :(得分:0)
要处理tyrus库中多个cookie的错误,我的解决方案如下:
ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest( Map<String, List<String>> headers ) {
// A bug in the tyrus library let concat multiple headers with a comma. This is wrong for cookies which needs to concat via semicolon
List<String> cookies = getMyCookies();
StringBuilder builder = new StringBuilder();
for( String cookie : cookies ) {
if( builder.length() > 0 ) {
builder.append( "; " ); // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie
}
builder.append( cookie );
}
headers.put( "Cookie", Arrays.asList( builder.toString() ) );
}
};