【问题标题】:How to send plain unescaped String with Spring's MessageSendingOperations?如何使用 Spring 的 MessageSendingOperations 发送普通的未转义字符串?
【发布时间】:2014-06-23 12:18:26
【问题描述】:

我正在使用 Spring 消息传递和 Spring Socket 4.0.5.RELEASE。

我想向代理发送一条纯字符串消息。事实证明,这样的 String 被转义了,例如在服务器端执行以下操作时:

private MessageSendingOperations<String> messagingTemplate;
messagingTemplate.convertAndSend("/app/someendpoint", "This is a String with a quotation mark: \". ");

然后订阅的 STOMP 客户端会收到以下消息:

<<< MESSAGE
content-type:application/json;charset=UTF-8
subscription:sub-0
message-id:l6dvrpro-3
destination:/app/someendpoint
content-length:46

"This is a String with a quotation mark: \". " 

因此有效载荷包括引号和转义引号。

如何发送未转义的“正常”字符串?

【问题讨论】:

    标签: spring stomp spring-messaging


    【解决方案1】:

    因此,您不希望将消息转换为 JSON。

    如果您的所有消息都需要它,请覆盖 WebSocketMessageBrokerConfigurer.configureMessageConverters() 以从活动 MessageConverters 列表中排除 JSON 转换器:

    @Override
    public boolean configureMessageConverters(List<MessageConverter> converters) {
        converters.add(new StringMessageConverter());
        return false; // Prevent registration of default converters
    }
    

    如果您只需要此消息,请尝试手动指定其内容类型:

    messagingTemplate.convertAndSend(
        "/app/someendpoint", 
        "This is a String with a quotation mark: \". ",
        Collections.singletonMap("content-type", "text/plain");
    

    【讨论】:

    • 我尝试了您的messagingTemplate.convertAndSend(..),但不幸的是,在我的情况下,它仍然会导致客户端收到带有content-type:application/json;charset=UTF-8 和转义字符串的消息...
    【解决方案2】:

    丑陋,但至少它可以工作,并且不需要任何特定的WebSocketMessageBrokerConfigurer 配置:

    String payload = "This is a String with a quotation mark: \". ";
    byte[] decodedPayload = message.getBytes();
    
    Map<String, Object> headers = new HashMap<>();
    headers.put("content-type", "text/plain");
    // alternatively, a JSON content type also works fine, e.g. when you need to send adhoc-generated custom JSON payloads: headers.put("content-type", "content-type:application/json;charset=UTF-8");
    GenericMessage<byte[]> message = new GenericMessage<>(decodedPayload, headers);
    messagingTemplate.send("/app/someendpoint", message);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 2014-08-06
      相关资源
      最近更新 更多