How to send a SOAP request using WebServiceTemplate?

前端 未结 5 795
温柔的废话
温柔的废话 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:02

    I tried many options and finally below one worked for me if you have to send soap header with authentication(Provided authentication object created by wsimport) and also need to set soapaction.

    public Response callWebService(String url, Object request)
    
    {
        Response res = null;
        log.info("The request object is " + request.toString());
    
        try {
            
            
    
            res = (Response) getWebServiceTemplate().marshalSendAndReceive(url, request,new WebServiceMessageCallback() {
                     @Override
                      public void doWithMessage(WebServiceMessage message) {
                        try {
                          // get the header from the SOAP message
                          SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader();
    
                          // create the header element
                          ObjectFactory factory = new ObjectFactory();
                          Authentication auth =
                              factory.createAuthentication();
                          auth.setUser("****");
                          auth.setPassword("******");
                         ((SoapMessage) message).setSoapAction(
                                    "soapAction");
    
                          JAXBElement headers =
                              factory.createAuthentication(auth);
    
                          // create a marshaller
                          JAXBContext context = JAXBContext.newInstance(Authentication.class);
                          Marshaller marshaller = context.createMarshaller();
    
                          // marshal the headers into the specified result
                          marshaller.marshal(headers, soapHeader.getResult());
                          
                        } catch (Exception e) {
                          log.error("error during marshalling of the SOAP headers", e);
                        }
                      }
                    });
    
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    
    }
    

提交回复
热议问题