0

我正在使用 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: \". " 

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

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

4

2 回答 2

1

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

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

@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");
于 2014-06-23T12:49:21.650 回答
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);
于 2014-06-24T10:45:53.747 回答