Tuesday, January 12, 2010

Soap Client with XML DOM

Below is a sample soap client, which can take in a XML DOM, which is got from a xml string.

String targetERP = "http://myserver.com/NewWebService/services/ServiceName";

SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
connection = (SOAPConnection)scf.createConnection();

// SOAPFactory sf = SOAPFactory.newInstance();

// Create the message
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage message = mf.createMessage();

SOAPPart soapPart = ((SOAPMessage) message).getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
// message body
SOAPBody body = envelope.getBody();

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

//strRequestXML is a XML string which may be generated by java.
ByteArrayInputStream x = new ByteArrayInputStream(strRequestXML.getBytes());
Document doc = db.parse(x);
body.addDocument(doc); // add the xml to the soap messahe body

((SOAPMessage) message).writeTo(System.out);
System.out.println("\n");
URL endpoint = new URL(targetERP);

SOAPMessage response = connection.call(message, endpoint);
// SOAPMessage response = connection.call("",
// endpoint);
connection.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.writeTo(baos);
responseStr = baos.toString();

Of course the imports are
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.soap.*;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

No comments:

Post a Comment