如何将 SOAP Headers 添加到 Spring Jax-WS Client?
2022-09-03 12:11:56
稍微优雅一点(仍然需要一个类转换):
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
}
}
注意:此示例已使用 Spring WS 2.1.4 进行了测试。
我仍然试图找到一种优雅的方法来添加标头,但是按照其他人的建议,我所做的是在WebServiceMessageCallBack()上使用Transformer。下面是一个示例代码:
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);
}
}
...
考虑到这是Spring的WS,它并不是很优雅。这并不直观。