如何将 SOAP Headers 添加到 Spring Jax-WS Client?

2022-09-03 12:11:56

如何将 SOAP 标头添加到 Spring Jax-WS 客户端?

具体来说,我有一个Jaxb对象,我想添加到头文件中,但xml示例将不胜感激。

我正在使用Spring的JaxWsPortProxyFactoryBean,这里描述了。另外,我正在生成我的客户端,如这里所述,它的工作减少了我需要添加的标头。

谢谢。


答案 1

稍微优雅一点(仍然需要一个类转换):

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 进行了测试。


答案 2

我仍然试图找到一种优雅的方法来添加标头,但是按照其他人的建议,我所做的是在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,它并不是很优雅。这并不直观。


推荐