'How to customize HTTP response for WebSocket upgrade request in Spring?

I have a WebSocket endpoint configured like this in my WebSocketConfigurer implementation

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new ExceptionWebSocketHandlerDecorator(myWebSocketHandler), "/ws/")
                .setAllowedOrigins("*")
                .addInterceptors(myHandshakeInterceptor);
    }

There are some checks in myWebSocketHandler#beforeHandshake and I would like to send an error message to the user in case the server decides to refuse to upgrade the connection. I've tried this

response.setStatusCode(HttpStatus.BAD_GATEWAY);
try {
    response.getBody().write("Error".getBytes());
    response.getBody().flush();
} catch (IOException e) {
    log.error("Error writing response", e);
}
return false;

The status code works, but the body is empty. How can I send it?

EDIT: turns out the problem was that I used Firefox console to check for the response and it didn't show me anything. If I use cURL to make the same request then everything works fine and I see the message I write to the response body!



Solution 1:[1]

To update response body you need to write your custom RequestUpateStrategy. As from spring official documentation from AbstractHandshakeHandler it says that:

The actual upgrade is delegated to a server-specific RequestUpgradeStrategy, which will update the response as necessary and initialize the WebSocket.

If you are using Tomcat as servlet container you can extend TomcatRequestUpgradeStrategyclass and provider your own logic how to handle websocket upgrade.

For each servlet container there is implementation of RequestUpgradeStrategy documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mykhailo Moskura