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.
This is an alternative solution:
public class YourServiceClient extends WebServiceGatewaySupport {
// custom header inner class
private final class CustomHeader implements WebServiceMessageCallback {
private String soapAction;
private long yourHeaderParameter1;
private long yourHeaderParameter2;
public CustomHeader(String soapAction, long yourHeaderParameter1, long yourHeaderParameter2) {
super();
if (!StringUtils.hasText(soapAction)) {
soapAction = "\"\"";
}
this.soapAction = soapAction;
this.yourHeaderParameter1 = yourHeaderParameter1;
this.yourHeaderParameter2 = yourHeaderParameter2;
}
@Override
public void doWithMessage(WebServiceMessage message) {
try {
// get the header from the SOAP message
SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader();
// create the header element
ObjectFactory factory = new ObjectFactory();
YourGeneratedHeaderEntity header = new YourGeneratedHeaderEntity();
header.setyourHeaderParameter1(yourHeaderParameter1);
header.setyourHeaderParameter2(yourHeaderParameter2);
JAXBElement headers = factory.createYourGeneratedHeaderEntity(header);
// create a marshaller
JAXBContext context = JAXBContext.newInstance(YourGeneratedHeaderEntity.class);
Marshaller marshaller = context.createMarshaller();
// set action
Assert.isInstanceOf(SoapMessage.class, message);
SoapMessage soapMessage = (SoapMessage) message;
soapMessage.setSoapAction(soapAction);
// marshal the headers into the specified result
marshaller.marshal(headers, soapHeader.getResult());
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
}
}
}
public YourEntityResponse getYourService(long yourHeaderParameter1, long yourHeaderParameter2) {
GetYourService request = new GetYourService();
YourEntityResponse response = (YourEntityResponse) getWebServiceTemplate()
.marshalSendAndReceive(request, new CustomHeader("https://your.service.asmx?WSDL", yourHeaderParameter1, yourHeaderParameter2));
return response;
}
}