How to send a SOAP request using WebServiceTemplate?

前端 未结 5 798
温柔的废话
温柔的废话 2020-11-30 07:50

I am trying to send a request to a SOAP webservice. I read this tutorial and prepared the following code. However, I am going to send different requests to multiple SOAP web

5条回答
  •  清歌不尽
    2020-11-30 08:05

    To send different SOAP requests to different SOAP services, you just need to make your WebServiceTemplate aware of all requests and responses it will have to process.

    Create a Java class for each request and response like so:

    package models;
    import javax.xml.bind.annotation.XmlRootElement;
    import java.io.Serializable;
    
    @XmlRootElement
    public class FlyRequest implements Serializable {
    
        private boolean nearByDeparture;
    
        public FlyRequest() {}
    
        public boolean isNearByDeparture() {
            return nearByDeparture;
        }
    
        public void setNearByDeparture(boolean nearByDeparture) {
            this.nearByDeparture = nearByDeparture;
        }
    }
    

    (The @XmlRootElement is because we use JAXB marshaller below; see Jaxb reference for more info).

    The setup of the template is done for example like so:

        SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance());
        messageFactory.afterPropertiesSet();
    
        WebServiceTemplate webServiceTemplate = new WebServiceTemplate(messageFactory);
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("models");
        marshaller.afterPropertiesSet();
    
        webServiceTemplate.setMarshaller(marshaller);
        webServiceTemplate.afterPropertiesSet();
    

    "models" is the name of the package where the Request/Responses classes are, so that jaxb can find them.

    Then you just instantiate the request of the class you want to perform the call, like so:

        // call fly service:
        FlyRequest flyRequest = new FlyRequest();
        flyRequest.setNearByDeparture(false);
        Object flyResponse = webServiceTemplate.marshalSendAndReceive("https://example.net/fly", flyRequest);
    
        // call purchase service:
        PurchaseRequest purchaseRequest = new PurchaseRequest();
        purchaseRequest.setPrice(100);
        Object purchaseResponse = webServiceTemplate.marshalSendAndReceive("https://example.net/purchase", purchaseRequest);
    

    Similarly, you can cast the response objects into your JAXB classes defined above.

提交回复
热议问题