Sunday, March 11, 2012

Spring - webServiceTemple

How to use webServiceTemplate to add Soap Header elements for webservice client:

       WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
        SaajSoapMessageFactory factory = new SaajSoapMessageFactory();
        factory.afterPropertiesSet();
        webServiceTemplate.setMessageFactory(factory);           
        Unmarshaller unm = (Unmarshaller)funnelMarshaller;
        webServiceTemplate.setMarshaller(funnelMarshaller);
        webServiceTemplate.setUnmarshaller(unm);
//Declare your own clientInterceptor in application-config.xml if required.
        webServiceTemplate.setInterceptors(new ClientInterceptor[]{myClientInterceptor});
        webServiceTemplate.setDefaultUri(myurl);
//get SoapAction


webServiceTemplate.marshalSendAndReceive(request, new WebServiceMessageCallback() {                   
            @Override
            public void doWithMessage(WebServiceMessage message) {
                try {                   
                    SoapMessage soapMessage = (SoapMessage)message;                   
                    soapMessage.setSoapAction(soapAction);
                    SoapHeader header = soapMessage.getSoapHeader();
                    SoapHeaderElement tokenId =  header.addHeaderElement(new QName("http://vzSFA.services.com/SecurityToken", "Token"));
                    tokenId.setText(token);                   
                                                          
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


myClientInterceptor:
    Just create a class that implements org.springframework.ws.client.support.interceptor.ClientInterceptor and override the following methods:
handleFault, handleRequest, handleResponse.

Interceptors are equivalent to adding Handlers to soapbinding. 

No comments:

Post a Comment