[英]SOLVED - How to customize HTTP response for WebSocket upgrade request in Spring?
I have a WebSocket endpoint configured like this in my WebSocketConfigurer
implementation我的
WebSocketConfigurer
实现中有一个像这样配置的 WebSocket 端点
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. myWebSocketHandler#beforeHandshake
有一些检查,如果服务器决定拒绝升级连接,我想向用户发送错误消息。 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.编辑:原来问题是我使用 Firefox 控制台来检查响应,但它没有显示任何内容。 If I use cURL to make the same request then everything works fine and I see the message I write to the response body!
如果我使用 cURL 发出相同的请求,那么一切正常,我会看到我写到响应正文的消息!
To update response body you need to write your custom RequestUpateStrategy.要更新响应正文,您需要编写自定义 RequestUpateStrategy。 As from spring official documentation from AbstractHandshakeHandler it says that:
从 AbstractHandshakeHandler 的 spring 官方文档来看,它说:
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 TomcatRequestUpgradeStrategy class and provider your own logic how to handle websocket upgrade.如果您使用 Tomcat 作为 servlet 容器,您可以扩展TomcatRequestUpgradeStrategy类并提供您自己的逻辑来处理 websocket 升级。
For each servlet container there is implementation of RequestUpgradeStrategy documentation对于每个 servlet 容器,都有 RequestUpgradeStrategy 文档的实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.