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



我正在使用 Tyrus 客户端包从我的 Java 应用程序中使用一个 websocket 端点,该端点需要在初始客户端请求中使用 cookie 标头。 浏览 Tyrus 客户端 API 文档和 Google 并没有让我走得太远。 任何想法如何做到这一点?

找到了我自己问题的解决方案,所以我想我会分享。 解决方案是在 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();

然后在后续调用 ClientManager.connectToServerClientManager.asyncConnectToServer 时使用此ClientEndpointConfig对象。

为了处理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() ) );
            }
        };

最新更新