Online Java Calling Soap Service - Yash-777/Axis1x_Soap GitHub Wiki
SOAP UI - Online SoapClient Calculator
SOAP:
<ns1:getSampleTextResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:com.yash777.HelloWorld">
<getSampleTextReturn xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">Sample Text</getSampleTextReturn>
</ns1:getSampleTextResponse>
Java:
<ns1:getSampleTextResponse soapenv:encodingStyle="http://www.w3.org/2003/05/soap-encoding" xmlns:ns1="urn:com.yash777.HelloWorld">
<ns2:result xmlns:ns2="http://www.w3.org/2003/05/soap-rpc">getSampleTextReturn</ns2:result>
<getSampleTextReturn xsi:type="ns3:string" xmlns:ns3="http://schemas.xmlsoap.org/soap/encoding/">Sample Text</getSampleTextReturn>
</ns1:getSampleTextResponse>
Pom.xml
<dependency>
<groupId>xml-security</groupId>
<artifactId>xmlsec</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.1</version>
</dependency>
package com.java.soap.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
// https://stackoverflow.com/questions/6799921/how-to-authenticate-soap-based-java-web-services
public class SOAP_Calculator {
public static void main(String[] args) throws Exception {
String xmlData =
"<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>";
//"<urn:getSampleText xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:com.yash777.HelloWorld\" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"/>";
//"<ns:GetCapabilities xmlns:ns=\"http://www.opengis.net/wps/1.0.0\" xmlns:ns1=\"http://www.opengis.net/ows/1.1\" service=\"WPS\" language=\"en\"> <ns:AcceptVersions> <ns1:Version>1</ns1:Version> </ns:AcceptVersions> </ns:GetCapabilities>";
String endPointUrl =
"http://www.dneonline.com/calculator.asmx";
//"http://localhost:8080/Axis1x_Soap/services/HelloWorld";
//"http://toolbox.webservice-energy.org:80/TOOLBOX/services/AIP3_PV_Impact";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
Document docBody = dBuilder.parse(ips);
//docBody.createElementNS(DSIG_NS, "ds");
System.out.println("Data Document: "+docBody.getDocumentElement());
// Protocol 1.1=SOAP-ENV Content-Type:text/xml; charset=utf-8, 1.2=env Content-Type:application/soap+xml; charset=utf-8
MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage soapMsg = messageFactory.createMessage();
//SOAPMessage soapMsg = SOAPMessageFactory1_1Impl.newInstance().createMessage();
SOAPPart soapPart = soapMsg.getSOAPPart();
SOAPEnvelope soapEnv = soapPart.getEnvelope();
SOAPBody soapBody = soapEnv.getBody();
//soapEnv.addNamespaceDeclaration("tem", "http://tempuri.org/");
// xmlns:urn="urn:com.yash777.HelloWorld"
//soapEnv.addNamespaceDeclaration("urn", "urn:com.yash777.HelloWorld");
soapBody.addDocument(docBody);
Element ownerDocument = soapPart.getDocumentElement();
String TSOXML = SOAPOperations.toStringDocument( ownerDocument.getOwnerDocument() );
TSOXML = TSOXML.replaceAll("env:", "soapenv:");
TSOXML = TSOXML.replaceAll(":env", ":soapenv");
System.out.println("TSOXML :"+TSOXML);
// Invoke the webService.
System.out.println("Request SOAP Message:");
soapMsg.writeTo(System.out);
System.out.println("\n");
//System.setProperty("javax.net.ssl.keyStore", "C:/Softwares/JDK/jdk1.8.0_121/jre/lib/security/cacerts");
//System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
//Service service = Service.create(wsdlURL, SERVICE_NAME);
/*java.net.URL endpointURL = new java.net.URL(soapEndpointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.1");
CalculatorSoapStub obj_axis = new CalculatorSoapStub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);*/
/*java.net.URL endpointURL = new java.net.URL("http://localhost:8080/Axis1x_Soap/services/HelloWorld");
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.1");
HelloWorldSoapBindingStub obj_axis = new HelloWorldSoapBindingStub(endpointURL, service);
String text = obj_axis.getSampleText();
System.out.println("Response: "+ text);*/
URL endpoint = getURL(endPointUrl);
MimeHeaders headers = soapMsg.getMimeHeaders();
//MimeHeaders headers = new MimeHeaders();
// SoapServerURI: http://www.dneonline.com/calculator.asmx
// SoapWSDL: http://www.dneonline.com/calculator.asmx?wsdl
/*<wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">
<wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="getSampleText">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="getSampleTextRequest">
<wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:com.yash777.HelloWorld" use="encoded"/>
</wsdl:input>
<wsdl:output name="getSampleTextResponse">
<wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:com.yash777.HelloWorld" use="encoded"/>
</wsdl:output>
</wsdl:operation>*/
// headers.addHeader("SoapBinding", "HelloWorldSoapBinding");// <wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">
// headers.addHeader("SOAPAction", "");
// headers.addHeader("MethodName", "getSampleText");
/*<wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="Add">
<soap12:operation soapAction="http://tempuri.org/Add" style="document"/>*/
headers.addHeader("SoapBinding", "CalculatorSoap");// <wsdl:binding name="CalculatorSoap" type="tns:CalculatorSoap">
headers.addHeader("MethodName", "Add");
headers.addHeader("SOAPAction", "http://tempuri.org/Add"); // "SOAPAction: "http://tempuri.org/Add"
headers.addHeader("Accept-Encoding", "gzip,deflate");
// Protocol 1.1=SOAP-ENV Content-Type:text/xml; charset=utf-8, 1.2=env Content-Type:application/soap+xml; charset=utf-8
SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
headers.addHeader("Content-Type", "text/xml; charset=utf-8");
} else {
System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
headers.addHeader("Content-Type", "application/soap+xml; charset=utf-8");
}
if (soapMsg.saveRequired()) {
System.out.println("Save Changes...");
soapMsg.saveChanges();
}
for (Iterator<?> iterator = headers.getAllHeaders(); iterator.hasNext();) {
MimeHeader mimeHeader = (MimeHeader) iterator.next();
System.out.format("%15s:%s \n", mimeHeader.getName(), mimeHeader.getValue());
}
/*AttachmentPart attachment = soapMsg.createAttachmentPart();
attachment.setContent("sm_content", "text/plain");
attachment.setContentId("[email protected]");
soapMsg.addAttachmentPart(attachment);*/
soapMsg.saveChanges();
/*SOAPMessage message = MessageFactory.newInstance()
.createMessage(headers, new ByteArrayInputStream(TSOXML.getBytes()));*/
SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
//connection.setTimeout(10000);
SOAPMessage resp = connection.call(soapMsg, endpoint);
/*SOAPMessage resp = SOAPOperations.sendSoapRequest_TruestAllCerts(endPointUrl, soapMsg);
*/
// https://stackoverflow.com/questions/38924073/soapexceptionimpl-bad-response-404not-found-if-i-dont-do-soapmessage-writetos
// com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Bad response: (404Not Found : Dueto wrong proxy info
ByteArrayOutputStream out = new ByteArrayOutputStream();
resp.writeTo(out);
// resp.writeTo(System.out);
String strMsg = new String(out.toByteArray());
System.out.println("Resp: "+ strMsg);
}
private static URL getURL(String endPointUrl) throws MalformedURLException {
String PROXY_ADDRESS = "127.0.0.1";
int PROXY_PORT = 0;
// System.setProperty("http.proxyHost", "myProxyServer.com");
// System.setProperty("http.proxyPort", "80");
System.setProperty("java.net.useSystemProxies", "true"); // https://stackoverflow.com/a/4599968/5081877
URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
// The url is the parent of this stream handler, so must
// create clone
URL clone = new URL(url.toString());
URLConnection connection = null;
if (PROXY_ADDRESS != null && PROXY_PORT != 0 ) { // https://stackoverflow.com/a/22533464/5081877
Socket socket = new Socket();
SocketAddress sockaddr = new InetSocketAddress(PROXY_ADDRESS, PROXY_PORT);
socket.connect(sockaddr, 10000);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(socket.getInetAddress(), PROXY_PORT));
if (proxy.address().toString().equals("0.0.0.0/0.0.0.0:80")) {
connection = clone.openConnection();
} else {
connection = clone.openConnection(proxy);
}
} else {
connection = clone.openConnection();
}
connection.setConnectTimeout(20 * 1000); // 5 sec
connection.setReadTimeout(20 * 1000); // 5 sec
// Custom header
//connection.addRequestProperty("Developer-Mood", "Happy");
//connection.connect();
return connection;
}
});
return endpoint;
}
}
package com.java.soap.util;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class SOAPOperations {
// Protocol 1.1=SOAP-ENV Content-Type:text/xml; charset=utf-8, 1.2=env Content-Type:application/soap+xml; charset=utf-8
public static final String SOAP_1_1_PROTOCOL = "SOAP 1.1 Protocol";
public static final String SOAP_1_2_PROTOCOL = "SOAP 1.2 Protocol";
// The namespace identifier for the SOAP envelope.
public static final String URI_NS_SOAP_1_1_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
public static final String URI_NS_SOAP_1_2_ENVELOPE = "http://www.w3.org/2003/05/soap-envelope";
// The media type of the <code>Content-Type</code> MIME header in SOAP
public static final String SOAP_1_1_CONTENT_TYPE = "text/xml";
public static final String SOAP_1_2_CONTENT_TYPE = "application/soap+xml";
static boolean OMIT_XML_DECLARATION = true;
static String soapXML = "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\">"
+ "<env:Body> "
+ "<product version=\"11.1.2.4.0\"> <!-- Data XML -->"
+ "<name>API Gateway</name> <company>Oracle</company> <description>SOA Security and Management</description>"
+ "</product> </env:Body> </env:Envelope>";
// dependency: groupId:xml-security, artifactId:xmlsec, version:1.3.0
// dependency: groupId:xalan, artifactId:xalan, version:2.7.1
public static void main(String[] args) throws Exception {
SOAPOperations obj = new SOAPOperations();
SOAPMessage soapMessage = obj.getSoapMessage(soapXML, true);
System.out.println("SOAP Message Object:\n"+soapMessage);
String soapMessageStr = obj.getSoapMessage(soapMessage);
System.out.println("SOAP Message String:\n"+soapMessageStr);
String soapBodyStr = obj.getSoapBody(soapMessage);
System.out.println("SOAP Body String:\n"+soapBodyStr);
}
public String getSoapBody(SOAPMessage soapMessage) throws Exception {
SOAPBody soapEnv = soapMessage.getSOAPBody();
Document ownerDocument = soapEnv.extractContentAsDocument();
String stringDocument = toStringDocument(ownerDocument);
return stringDocument;
}
public String getSoapMessage(SOAPMessage soapMessage) throws Exception {
SOAPEnvelope soapEnv = soapMessage.getSOAPPart().getEnvelope();
Document ownerDocument = soapEnv.getOwnerDocument();
String stringDocument = toStringDocument(ownerDocument);
return stringDocument;
}
public SOAPMessage getSoapMessage(String xmlData, boolean isToIgnoringComments) throws Exception {
if (isToIgnoringComments) {
Document doc = getDocument(xmlData); // SOAP MSG removing comment elements
xmlData = toStringDocument(doc);
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlData.getBytes());
MimeHeaders mimeHeaders = new MimeHeaders();
SOAPMessage message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(mimeHeaders, byteArrayInputStream);
return message;
}
public static Document getDocument(String xmlData) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
Document doc = dBuilder.parse(ips);
return doc;
}
public static String toStringDocument(Document doc) throws TransformerException {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
if (OMIT_XML_DECLARATION) {
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
} else {
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
}
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString(); // sw.getBuffer().toString();
}
// https://automationrhapsody.com/send-soap-request-over-https-without-valid-certificates/
public static SOAPMessage sendSoapRequest(String endpointUrl, SOAPMessage request) throws MalformedURLException {
try {
// Send HTTP SOAP request and get response
SOAPConnection soapConnection = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage response = soapConnection.call(request, new URL(endpointUrl));
// Close connection
soapConnection.close();
return response;
} catch (SOAPException e) {
e.printStackTrace();
}
return null;
}
public static SOAPMessage sendSoapRequestHttps(String endpointUrl, SOAPMessage request) {
try {
final boolean isHttps = endpointUrl.toLowerCase().startsWith("https");
HttpsURLConnection httpsConnection = null;
// Open HTTPS connection
if (isHttps) {
// Open HTTPS connection
URL url = new URL(endpointUrl);
httpsConnection = (HttpsURLConnection) url.openConnection();
// Trust all hosts
httpsConnection.setHostnameVerifier(new TrustAllHosts());
// Connect
httpsConnection.connect();
}
// Send HTTP SOAP request and get response
SOAPConnection soapConnection = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage response = soapConnection.call(request, new URL(endpointUrl));
// Close connection
soapConnection.close();
// Close HTTPS connection
if (isHttps) {
httpsConnection.disconnect();
}
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Dummy class implementing HostnameVerifier to trust all host names
*/
private static class TrustAllHosts implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static SOAPMessage sendSoapRequest_TruestAllCerts(String endpointUrl, SOAPMessage request) {
try {
final boolean isHttps = endpointUrl.toLowerCase().startsWith("https");
HttpsURLConnection httpsConnection = null;
// Open HTTPS connection
if (isHttps) {
// Create SSL context and trust all certificates
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager[] trustAll = new TrustManager[] {new TrustAllCertificates()};
sslContext.init(null, trustAll, new java.security.SecureRandom());
// Set trust all certificates context to HttpsURLConnection
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
// Open HTTPS connection
URL url = new URL(endpointUrl);
httpsConnection = (HttpsURLConnection) url.openConnection();
// Trust all hosts
httpsConnection.setHostnameVerifier(new TrustAllHosts());
// Connect
httpsConnection.connect();
}
// Send HTTP SOAP request and get response
SOAPConnection soapConnection = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage response = soapConnection.call(request, endpointUrl);
// Close connection
soapConnection.close();
// Close HTTPS connection
if (isHttps) {
httpsConnection.disconnect();
}
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Dummy class implementing X509TrustManager to trust all certificates
*/
private static class TrustAllCertificates implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}