3

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

4

2 回答 2

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

然后在您对orClientEndpointConfig的后续调用中使用此对象。ClientManager.connectToServerClientManager.asyncConnectToServer

于 2015-01-26T03:42:26.310 回答
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() ) );
            }
        };
于 2018-03-08T09:16:53.117 回答