如何从 SOAP 消息中删除空 header?

How to remove empty header from SOAP message?

我正在使用 Spring-WS 来使用 Web 服务,如果 SOAP 信封有空 header 元素,它会抱怨。我发现默认的 SOAPMessage 实现增加了一个。

如何删除它?

提前致谢

http://docs.oracle.com/javaee/5/tutorial/doc/bnbhr.html:

The next line is an empty SOAP header. You could remove it by calling header.detachNode after the getSOAPHeader call.

所以这里是普通 SAAJ 的解决方案:

        MessageFactory messageFactory = MessageFactory.newInstance("SOAP 1.2 Protocol");
        SOAPMessage message = messageFactory.createMessage();
        message.getSOAPHeader().detachNode(); // suppress empty header

这是使用 spring-ws WebServiceMessageCallback based on this thread:

的解决方案
public void marshalWithSoapActionHeader(MyObject o) {

    webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {

        public void doWithMessage(WebServiceMessage message) {
            SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
            SOAPMessage soapMessage = saajSoapMessage.getSaajMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();
            SOAPHeader header = soapMessage.getSOAPHeader(); 
            header.detachNode();
        }
    });
}