提问者:小点点

如何使用Tyrusjava客户端在初始WebSocket客户端请求中包含cookie?


我正在使用Tyrus客户端包从我的Java应用程序中使用一个websocketendpoint,该endpoint在初始客户端请求中需要一个cookie标头。查看Tyrus客户端API文档和谷歌搜索并没有让我走得太远。有什么想法可以做到这一点吗?


共2个答案

匿名用户

找到了我自己问题的解决方案,所以想分享一下。解决方案是在ClientEndpoint Config上设置一个自定义配置器,并覆盖该配置器中的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();

然后在后续调用ClientManager. connect tToServerClientManager.asyncConnectToServer时使用此ClientManager对象。

匿名用户

为了处理tyrus库中多个cookie的bug,我的解决方案如下所示:

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