Calling any service using WebService


A Service can be called in different ways, for example using SCA , Webservice or Messaging models.
In some specific requirement we can call it using standalone java program, input for this program would be the endpoint & message (input) to be passed.


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


public class SendSoapMessage {
public static String sendMessage (String message) {
String response = "";


try {
SOAPMessage soapMessage = convertSoapStringMsgToSoapMessage(message);
soapMessage.saveChanges();
SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = connectionFactory.createConnection();
URL endpoint = new URL ("http://localhost:9081/TestWeb/sca/SampleExport1?wsdl"); //endpoint address 
SOAPMessage resp = soapConnection.call(soapMessage, endpoint);
resp.writeTo( System.out );
soapConnection.close();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
resp.writeTo(byteArrayOutputStream);
response = new String(byteArrayOutputStream.toByteArray());
}


catch (java.io.IOException ioe) {
ioe.printStackTrace();
}
catch (SOAPException soape) {
soape.printStackTrace();
}
return response;
}


public static void main (String args[]) {
String response=sendMessage(" <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://Test/Sample\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soapenv:Body> <q0:operation1>  <input1>87</input1>   </q0:operation1>  </soapenv:Body>  </soapenv:Envelope>"); // fill your input to be posted.
//in above example name of the operation is operation1 & input is input1
}


public static SOAPMessage convertSoapStringMsgToSoapMessage (String soapText) {
try {
MessageFactory msgFactory  = MessageFactory.newInstance();  
SOAPMessage message = msgFactory.createMessage();  
SOAPPart soapPart = message.getSOAPPart();  
byte[] buffer  = soapText.getBytes();  
ByteArrayInputStream stream  = new ByteArrayInputStream(buffer);  
StreamSource source = new StreamSource(stream);  
soapPart.setContent(source);  
message.writeTo(System.out); 
return message;
}
catch(Exception e)
{return null;}

}
}

No comments:

Post a Comment