如何使用Spring的MessageSendingOperations发送普通的非转义字符串?

时间:2014-06-23 12:18:26

标签: spring stomp spring-messaging

我正在使用Spring Messaging和Spring Socket 4.0.5.RELEASE

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

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: \". " 

因此,有效负载包括周围的引号和转义的引号。

如何发送未转义的“普通”字符串?

2 个答案:

答案 0 :(得分:1)

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

如果您的所有邮件都需要它,请覆盖WebSocketMessageBrokerConfigurer.configureMessageConverters()以从活动MessageConverter列表中排除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");

答案 1 :(得分:0)

很丑,但至少它正在运行,并且不需要任何特定的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);