Search code examples
soapspring-integrationspring-ws

Customizing Spring Integration Web Service SOAP Envelope/Header


I am trying to send a SOAP request using Spring Integration like

<int:chain input-channel="wsOutChannel" output-channel="stdoutChannel">
    <int-ws:header-enricher>
        <int-ws:soap-action value="..."/>
    </int-ws:header-enricher>
    <int-ws:outbound-gateway
            uri="..."/>
</int:chain>

but you can only add the SOAP body, and Spring Integration adds the envelope, header, and body tags like

<SOAP-ENV:Envelope>
    <SOAP-ENV:Header>
        <SOAP-ENV:Body>
            ...
        </SOAP-ENV:Body>
    <SOAP-ENV:Header>
</SOAP-ENV:Envelope>

I need to customize the envelope and header tags with specific attributes, for example:

<soapenv:Envelope attribute1="value1" attribute2="value2">

and child elements, for example:

<soapenv:Header>
    <child>...<child>
<soapenv:Header>

Is this possible with Spring Integration Web Services, or should I not use int-ws:outbound-gateway and take a different approach?


Solution

  • You can add a ClientInterceptor (via the interceptor attribute) which allows you to modify the request before it's sent out.

    EDIT

    @Artem's suggestion is simpler but the interceptor gives you access to the response too; but either way, the code is similar.

    For the interceptor:

    public class MyInterceptor extends ClientInterceptorAdapter {
    
        @Override
        public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
            SoapMessage request = (SoapMessage) messageContext.getRequest();
            SoapEnvelope envelope = request.getEnvelope();
            envelope.addAttribute(new QName("foo"), "bar");
            SoapHeader header = envelope.getHeader();
            header.addHeaderElement(new QName("http://fiz/buz", "baz"));
            return super.handleRequest(messageContext);
        }
    
    }
    

    For the callback version:

    @Override
    public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
        SoapEnvelope envelope = ((SoapMessage) message).getEnvelope();
        envelope.addAttribute(new QName("foo"), "bar");
        SoapHeader header = envelope.getHeader();
        header.addHeaderElement(new QName("http://fiz/buz", "baz"));
    }