Reputation: 259
I need to generate a Soap request in Java. This is the xml file that I need to generate and pass through:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns="website"
xmlns:com="website/Common"
xmlns:xm="http://www.w3.org/2005/05/xmlmime">
<soapenv:Header/>
<soapenv:Body>
<ns:RequestName>
<ns:model>
<ns:keys query="myquery;" ></ns:keys>
<ns:instance></ns:instance>
</ns:model>
</ns:RequestName>
</soapenv:Body>
</soapenv:Envelope>
I am aware that there are other methods of doing this, such as wsimport, but I would like to know how to do it this way. My this way way, I mean what is the correct Java syntax in create the xml file for a Soap Request. Here is some very basic syntax:
SOAPMessage message = messageFactory.createMessage();
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
// Here is the XML it produces:
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
...
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Upvotes: 1
Views: 2357
Reputation: 2335
You can try with following code:
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("ns", "website");
envelope.addNamespaceDeclaration("com", "website/Common");
envelope.addNamespaceDeclaration("xm", "http://www.w3.org/2005/05/xmlmime");
SOAPBody soapBody = envelope.getBody();
SOAPElement element = soapBody.addChildElement("RequestName", "ns");
SOAPElement modelElement = element.addChildElement("model", "ns");
SOAPElement soapElement = modelElement.addChildElement("keys", "ns");
soapElement.addAttribute(envelope.createName("query"), "myquery;");
modelElement.addChildElement("instance", "ns");
soapMessage.saveChanges();
soapMessage.writeTo(System.out);
This will produce following output:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:com="website/Common"
xmlns:ns="website"
xmlns:xm="http://www.w3.org/2005/05/xmlmime">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns:RequestName>
<ns:model>
<ns:keys query="myquery;"/>
<ns:instance/>
</ns:model>
</ns:RequestName>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Upvotes: 5