Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
Balthorium Avatar asked Jan 17 '26 22:01

Balthorium


1 Answers

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.

like image 51
Balthorium Avatar answered Jan 21 '26 06:01

Balthorium