How to add SOAP Headers to Spring Jax-WS Client?

Brandon picture Brandon · Oct 28, 2010 · Viewed 17.8k times · Source

How can I add SOAP Headers to Spring Jax-WS Client?

Specifically, I have a Jaxb object I would like to add to the header but xml examples would be appreciated.

I am using Spring's JaxWsPortProxyFactoryBean described here. Also, I am generating my client as described here which is working less the headers I need to add.

Thank you.

Answer

user3078523 picture user3078523 · Jan 3, 2014

A little bit more elegant (still a class cast is required):

public void doWithMessage(WebServiceMessage message) {
    try {
        SOAPMessage soapMessage = ((SaajSoapMessage)message).getSaajMessage();
        SOAPHeader header = soapMessage.getSOAPHeader();
        SOAPHeaderElement security = header.addHeaderElement(new QName("http://schemas.xmlsoap.org/ws/2003/06/secext", "Security", "wsse"));
        SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse");
        SOAPElement username = usernameToken.addChildElement("Username", "wsse");
        SOAPElement password = usernameToken.addChildElement("Password", "wsse");

        username.setTextContent(someUsername);
        password.setTextContent(somePassword);
    } catch (Exception e) {
       //... handle appropriately
    }
}

Note: This example has been testes with Spring WS 2.1.4.