简体   繁体   中英

Writing an XML SOAP message in Java

I have the following method that accepts xml and I do some data feeding with the content. I am supposed to return a SOAP message as well, something along these lines:

<ow-e:Envelope revision='2.0' xmlns:ow-e='http://www.url.com/test-envelope'>
   <ow-e:Header>
      <ow-e:Properties>
         <ow-e:SentAt>2004-12-14T13:54:36</ow-e:SentAt>
         <ow-e:Topic>SOME_STRING</ow-e:Topic>
      </ow-e:Properties>
   </ow-e:Header>
</ow-e:Envelope>

So right now what I am doing is the following:

String some_string = "qwe";
String response = "";

response = "<ow-e:Envelope revision='2.0' xmlns:ow-e='http://www.url.com/test-envelope'><ow-e:Header><ow-e:Properties><ow-e:SentAt>2004-12-14T13:54:36</ow-e:SentAt><ow-e:Topic>" + some_string + "</ow-e:Topic></ow-e:Properties></ow-e:Header></ow-e:Envelope>";

return response;

Which is absolutely terrible. Any idea how I can actually make it more bearable? Using a framework is not an option at the moment.

This is the first time I am dealing with SOAP messages/responses and it feels like hell coming from REST. I probably need to create some kind of hierarchy to populate the values correctly, but I am not sure how it can be done just by using Java without any frameworks.

You mentioned using frameworks is not an option, but something more lightweight may be available in your platform:

  • JAXB . JAXB allows you to map Java classes to XML representations using annotations. It's far better than doing marshaling and unmarshaling by hand or by concatenating or parsing strings. With properly structured and annotated POJOs, JAXB can handle things for you. You might even be able to cheat and use xjc with your WSDL file to create annotated classes with the -wsdl option (experimental though).
  • SAAJ . Bluntly put, SAAJ is just like a specific builder and parser for SOAP messages. It will handle the structure and namespaces for you. Speaking of which...

... the example you are showing isn't really valid SOAP message. SOAP is a protocol. You need to properly format it and use the right namespaces otherwise you are just returning some XML messages that look like SOAP, but aren't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM