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.
To create a JAX-WS handler to access SOAP header information, first create a basic Java API for XML Web Services (JAX-WS) handlers for your export or import. It will create stubs for the methods. You next need to implement the handleMessage method.
The SOAP <Header> is an optional element in a SOAP message. It is used to pass application-related information that is to be processed by SOAP nodes along the message path. The immediate child elements of the <Header> element are called header blocks.
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.
I'm still trying to find an elegant way to add headers, but what I do as suggested by others is to use a Transformer on the WebServiceMessageCallBack(). Here's an example code:
JAXBElement<GetDeletedResponse> result = (JAXBElement<GetDeletedResponse>) webServiceTemplate.marshalSendAndReceive(request, new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage webServiceMessage) {
try {
SoapMessage soapMessage = (SoapMessage) webServiceMessage;
soapMessage.setSoapAction("getDeleted");
SoapHeader header = soapMessage.getSoapHeader();
StringSource headerSource = new StringSource("<account>\n" +
"<username>"+"johnsmith"+"</username>\n" +
"<password>"+"1234"+"</password>\n" +
"</account>");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(headerSource, header.getResult());
} catch (Exception e) {
new RuntimeException(e);
}
}
...
It's not really elegant, considering this is Spring's WS. It's not intuitive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With