Balthorium
Balthorium

Reputation: 99

How to include a cookie in the initial WebSocket client request using Tyrus java client?

I'm using the Tyrus client package to consume, from my Java application, a websocket endpoint that requires a cookie header in the initial client request. Looking through the Tyrus client API docs and Google'ing around hasn't got me too far. Any ideas how one might go about doing this?

Upvotes: 3

Views: 2841

Answers (2)

Horcrux7
Horcrux7

Reputation: 24447

To handle the bug with multiple cookies in the tyrus library my solution look like:

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

Upvotes: 0

Balthorium
Balthorium

Reputation: 99

Found a solution to my own question, so figured I'd share. The solution is to set a custom configurator on the ClientEndpointConfig and override the beforeRequest method in that configurator to add the cookie header.

For example:

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

Then use this ClientEndpointConfig object in your subsequent call to ClientManager.connectToServer or ClientManager.asyncConnectToServer.

Upvotes: 3

Related Questions