title: Send body and header parameters with Spring web service
body: <p>I'm new working with Spring, I'm trying  to send two parameters in a soap message, the first parameter is the header where I want to send a token and the second parameter is the body where I send a fixed parameter (the facade).</p>
  
  <ul>
  <li>"HEADER"  123456789asdfghjkl "HEADER" (that's the token)</li>
  <li><p>"BODY"   facadeMethod  "BODY"</p>
  
  <p>I'm not able to obtain an answer from a customer Web service with my Java code. I've tried some tests with SOAPUI and I've obtained always a result when I do it with the SOAPUI (I will put the example in the last section). </p></li>
  </ul>
  
  <p>I have one "main" class where I want to send my soap message injecting the spring bean with the two parameters. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>@Component
  public class CustomerService { 
   
   private WebServiceTemplate webServiceTemplate;
  
  @Autowired
      public void CustomerService(WebServiceTemplate webServiceTemplate) {
          this.webServiceTemplate = webServiceTemplate;
      }
   
   public String sendMyToken(String token) {
    tokenGETSessionLogged logear = new tokenGETSessionLogged();
    
    String exit= "sendMyToken(String token)";
    
    
    final String soapAction = "http://www.CustomerCompany.com/webService/Direction/OfTheWebService/Security/Method/forLogging/withToken/tokenGETSessionLogged";
    
    URI uri1=null;
    
    
    
    
    
    String uri="http://myCompanyURI.org/WebService/ToLoggin/Listen_To_Client_Request/";
    
    HttpComponentsMessageSender mySender = new HttpComponentsMessageSender();
    
    mySender.setConnectionTimeout(800000);
    
    try {
     uri1 = new URI ("http://myCompanyURI.org/WebService/ToLoggin/Listen_To_Client_Request/");
     mySender.createConnection(uri1);
    } catch (URISyntaxException e1) {
     // TODO Auto-generated catch block
    
     e1.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     
    }
    
    
    try {
     
     
     webServiceTemplate.setMessageSender(mySender);
     
    }catch(Exception e) {
     
    }
    
    try {
     
     
     logear.setFacade("FacadeSecuritymethod");
     
     
     String headYBody=token + logear.getFacade();
     tokenGETSessionLogged answer= (tokenGETSessionLogged)webServiceTemplate.marshalSendAndReceive(uri, headYBody, new SoapActionCallback(soapAction));
    
      exit= exit+ answer.toString();
     
    }catch (WebServiceTransportException ex) {
     
    }
    return exit;
   }
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>And my other class where I've declared my beans variables is:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>public class ClientApp {
  
  
   @Bean
   public Jaxb2Marshaller marshaller() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setContextPath("com.xx.soap.model");
    return marshaller;
   }
  @Bean
      public WebServiceTemplate webServiceTemplate() throws Exception {
  
          WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
          webServiceTemplate.setMarshaller(marshaller());
          webServiceTemplate.setUnmarshaller(marshaller());
          webServiceTemplate.setDefaultUri(
                  "http://myCompanyURI.org/WebService/ToLoggin/Listen_To_Client_Request/");
          webServiceTemplate.setMessageSender(httpComponentsMessageSender());
          return webServiceTemplate;
      }
  
  
  @Bean
  public HttpComponentsMessageSender httpComponentsMessageSender() throws Exception {
    HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
    httpComponentsMessageSender.setHttpClient(httpClient());
   
  
    return httpComponentsMessageSender;
  }
  public HttpClient httpClient() throws Exception {
   HttpClient cl= HttpClients.createDefault();
   
   return cl;
        
    }
  
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Can somebody tell my what I'm doing wrong???</p>
  
  <p>Of course I've checked a lot of sources but didn't helped me to send the body and the header: </p>
  
  <p><a href="https://stackoverflow.com/questions/9284024/spring-web-service-template-add-username-token">Spring Web Service Template: Add username token</a></p>
  
  <p><a href="https://www.codenotfound.com/spring-ws-https-client-server-example.html" rel="nofollow noreferrer">https://www.codenotfound.com/spring-ws-https-client-server-example.html</a></p>
  
  <p>And just In case I want to put an example of the SOAPUI message I send. What I Really want is to emulate this in Java, this shouldn't be so difficult:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.CustomerCompany.com/webService/Direction/OfTheWebService/Security/Method/forLogging/withToken/tokenGETSessionL"&gt;
     &lt;soapenv:Header&gt;
        &lt;wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;                                         
        &lt;wsse:BinarySecurityToken&gt;1234exampleoftokenIWantToSend789045678456cvbty&lt;/wsse:BinarySecurityToken&gt;
        &lt;/wsse:Security&gt;
     &lt;/soapenv:Header&gt;
     &lt;soapenv:Body&gt;
        &lt;v1:tokenGETSessionLogged facade="FacadeSecuritymethod"/&gt;
     &lt;/soapenv:Body&gt;
  &lt;/soapenv:Envelope&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Well I'm not good at posting but I'll do my best to explain how I solved it.</p>
  
  <p>First what you need is a webInitializer Class in order to tell your service to correctly call the Controller where your spring bean will be created. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>public class WebInitializer implements WebApplicationInitializer {
      
      @Override
      public void onStartup(ServletContext servletContext) throws ServletException {        
          AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();  
          context.register(Config.class);  
          context.setServletContext(servletContext);    
          Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));  
          servlet.addMapping("/authentication");  
          servlet.setLoadOnStartup(1);
      }
     
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>The default controller or Controller class is where you have to create the object where you will build the entire message with the header and the body. 
  As you can see the class will be identified with the parameter authentication</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>@Controller
  public class DefaultController {
      /** The Constant LOG. */
      private static final Logger LOGGER = LoggerFactory
              .getLogger(DefaultController.class);
      
      @Autowired
      private SoapService messageservice ;
      
     @RequestMapping(value = "/authentication", method = RequestMethod.GET)
     public String index(ModelMap map, @RequestParam(value="token") String token) {
      Properties prop= new Properties(); 
      String back= "MESSAGESERVICE";
      Book myLog=null;
         String pathLog= " ";
         try {
      //declare a new log file 
          pathLog=System.getProperty("catalina.home");
          pathLog=pathLog+"config.properties";// I saved a config file where I set the place where I set the trace file for the log
          prop.load(new FileReader(pathLog));
          String path = new File(".").getCanonicalPath();//this file is not relevant for this example but maybe help you
          
          path=prop.getProperty("LOGGERPATH");
          pathLog=path;
          myLog= new Book(pathLog);
          myLog.logger.warning("Starting the SOAP operation for send Spring message");
          
             Input input = new Input();;
             input.setToken(token);
             
             String name="empty";
             name=token;
            
             
             
             GetLoggedUIDResponse s = messageservice.SendMSG(input,  myLog);//here I call my message constructor method
             String k=s.getMethodResult();
             myLog.logger.warning("Result of operation "+k);
             
            
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    back="message";
   }
         
         
         
         return back;
     }
      
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>In this class I will call  the method SendMSG where I will construct the whole message. (body + header). This method will call a new class where I will create the SOAP message that my web service need to recive (messageservice.SendMSG)</p>
  
  <p>I've got another class () where the method SendMSG is created.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>@Component
  public class MessageServiceSOAP extends WebServiceGatewaySupport {
  
   
      
   
   private WebServiceTemplate webServiceTemplate;
  
   @Autowired
   public void SmsService(WebServiceTemplate webServiceTemplate) {
    this.webServiceTemplate = webServiceTemplate;
   }
  
   
  
   public GetLoggedUIDResponse SendMSG(Input input, Log2Sev myLog) {
     
    tokenGETSessionLogged  request = new tokenGETSessionLogged ();
    tokenGETSessionLogged Response returnObj = new tokenGETSessionLogged Response();
    
  
    
    try {
     String soapAction = " ";
     
     String pathLog="";
     Properties p= new Properties(); 
     pathLog=System.getProperty("catalina.home");//properties file where I get my parameters
     pathLog=pathLog+"\\config.properties";
     p.load(new FileReader(pathLog));
         soapAction="http://www.CustomerCompany.com/webService/Direction/OfTheWebService/Security/Method/forLogging/withToken/tokenGETSessionLogged";
     HttpComponentsMessageSender sender = new HttpComponentsMessageSender();
     sender.setConnectionTimeout(100000);
  
    
     String myToken=input.getToken();//the token you will use
     
     
     webServiceTemplate.setMessageSender(sender);
     try {
      request.setFacade("ACFACSEGSecurity");
  
      SoapActionCallback actionCallBack = CallBackSOAPActionBuild(soapAction, myToken);
  
     
       returnObj = (tokenGETSessionLogged Response) webServiceTemplate
        .marshalSendAndReceive(request, actionCallBack);
  
      
      
      return returnObj;
     } catch (WebServiceTransportException ex) {
      
      returnObj.setMethodResult("excepcion transporte");
     } catch (SoapFaultClientException ex) {
      
      returnObj.setMethodResult("excepcion soapCliente");
     }
  
    } catch (Exception e) {
     e.printStackTrace();
     returnObj.setMethodResult("excepcion");
    }
    
    return returnObj;
  
   }
  
   public SoapActionCallback CallBackSOAPActionBuild(final String soapAction, String myToken) {
  
    SoapActionCallback actionCallBack = new SoapActionCallback(soapAction);
    try {
     actionCallBack = new SoapActionCallback(soapAction) {
      public void doWithMessage(WebServiceMessage msgSend) {
       SoapMessage msgSOAP = (SoapMessage) msgSend;
       SoapHeader soapHeader = msgSOAP.getSoapHeader();
  
       try {
  
        ;
  
        // this is the part for the header 
        StringSource headerSource = new StringSource(
          // "&lt;soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http:URI/From/customer/secutrity/facade"&gt;\n" +
          //"&lt;soapenv:Header&gt;\n" +
           "&lt;wsse:Security xmlns:wsse=\"http://wsSecutirtyFilewithExtension.xsd\"&gt;;\n"
          + "&lt;wsse:BinarySecurityToken&gt;"+ myToken +"&lt;/wsse:BinarySecurityToken&gt;\n"
          + "&lt;/wsse:Security&gt;\n"  
          //"&lt;/soapenv:Header&gt;"
          );
       
        Transformer trnsfr = TransformerFactory.newInstance().newTransformer();
        transformer.transform(headerSource, soapHeader.getResult());
  
        msgSOAP.setSoapAction(soapAction);
       } catch (Exception e) {
        e.printStackTrace();
       }
      }
     };
    } catch (SoapFaultClientException sfce) {
     sfce.printStackTrace();
    } catch (WebServiceIOException we) {
     we.printStackTrace();
    } catch (Exception e) {
     e.printStackTrace();
    }
    return actionCallBack;
   }
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here I will create the object whit header and body parameter, this is the main call where my problem was. Take in consideration that I worte several dummy parameters so this code makes no sense, you have to replace the parameters with the parameters that the client will provide to you. Form example the soapAction, the URI of the web service, etc. </p>
  
  <p>Here I've got a method (CallBackSOAPActionBuild) that creates the header of the message where myToken is inyected in order to validate the user in the web service. The user token will be sended with the uri for the .xsd file and also the URI of the facade of the WS. </p>
  
  <p>Mind that I've changed the code to be simplier for readers as my code had way more functions that were no necessary. </p>