我正在使用Interceptor来获取Authorization标头,但是presend方法在建立连接和关闭连接时都在执行。问题是,当它关闭时,标头将引发null异常,我应该首先检查null还是有一种更好的方法来停止连接,以便不执行preSend方法?我的配置:
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/api/chat/message")
.setAllowedOrigins("*");
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(getWebSocketInterceptor());
}
private WebSocketInterceptor getWebSocketInterceptor(){
return new WebSocketInterceptor();
}
我的WebSocketInterceptor:
public class WebSocketInterceptor implements ChannelInterceptor, HandshakeInterceptor {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
MessageHeaders headers = message.getHeaders();
MultiValueMap<String, String> multiValueMap = headers.get(StompHeaderAccessor.NATIVE_HEADERS,MultiValueMap.class);
for(Map.Entry<String, List<String>> head : multiValueMap.entrySet()) {
System.out.println(head.getKey());
if(head.getKey().equals("Authorization")){
System.out.println(head.getValue());
}
}
return message;
}
答案 0 :(得分:0)
我找到了如何在preSend中检查连接类型的方法,也只是从StompHeaderAccessor中获取标头:
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
List<String> authorization1 = accessor.getNativeHeader("Authorization");
}