如何为 JMS 消息设置 Content-Type header

How to set Content-Type header for JMS message

我们有一个 Java 应用程序,它通过 IBM WebSphere MQ 发送 JMS 消息。消费者应用程序需要将消息内容类型设置为 "application/json"。我该怎么做?

我查看了一些参考资料,似乎我可以通过方法 "setStringProperty(headerKey, headerName)" 设置额外的 header,例如

Message jmsMsg = session.createTextMessage(msgStr);
jmsMsg.setStringProperty("Content-Type", "application/json");

问题是 "Content-Type" 不是有效的 属性 密钥,因为它包含“-”字符。

这可以用代码完成吗?或者它实际上是在 queue 设置中配置的?

属性 名称 "Content-Type" 有一个“-”字符。根据 JMS 规范,属性 名称可以包含 Java Character.isJavaIdentifierPart 方法 returns 和 true 的任何字符。对于'-'字符isJavaIdentifierPart方法returnsfalse。因此,setStringProperty("Content-Type", "application/json") 方法调用失败并出现以下异常。

com.ibm.msg.client.jms.DetailedMessageFormatException: JMSCC0049: The property name 'Content-Type' is not a valid Java(tm) identifier.
The supplied property name does not conform to the allowed format described in the JMS specification.
Check the characters used in the property name and modify as necessary.

如果可以更改接收应用程序,您可以选择 "Content_Type"(使用下划线)作为 属性 名称而不是 "Content-Type"

作为 SOAP 格式的示例,w3c 要求使用名为 "SOAPJMS_contentType" (http://www.w3.org/TR/soapjms/) 的 JMS 属性。看起来标准中没有关于 JSON 格式的内容,但是您可以这样使用名称。 IBM JMS 库将正确处理此类名称。