Skip to content

Instantly share code, notes, and snippets.

@sandeepkunkunuru
Last active September 5, 2019 09:56
Show Gist options
  • Save sandeepkunkunuru/7030828 to your computer and use it in GitHub Desktop.
Save sandeepkunkunuru/7030828 to your computer and use it in GitHub Desktop.
WebService - Document(SOAP) mode invocation - https - Example - from Scratch - Without referencing any library specific or generated classes e.g. classes of axis, axis2, cxf etc.
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
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.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.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
public class SOAPClient {
private static final String APP_TOKEN = "";
private static final String PASSWORD = "";
private static final String USERNAME = "";
private static final int CLIENT_LOGIN = 0;
private static final String serverURI = "https://.../v01";
private static final String url = "https://.../service.asmx";
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = invokeAction(soapConnection, CLIENT_LOGIN, USERNAME, PASSWORD);
String authToken = getAuthToken(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage invokeAction(SOAPConnection soapConnection,
int action, String... args) throws SOAPException,
KeyManagementException, NoSuchAlgorithmException, IOException {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("q0", serverURI);
envelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
envelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");
switch (action) {
case CLIENT_LOGIN:
soapMessage = createClientLoginRequest(soapMessage, args);
break;
default:
break;
}
doTrustToCertificates();
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapConnection.call(soapMessage, url);
}
private static SOAPMessage createClientLoginRequest(SOAPMessage soapMessage,
String ...args) throws SOAPException,
KeyManagementException, NoSuchAlgorithmException, IOException {
SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("clientLogin", "q0");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("username","q0");
soapBodyElem1.addTextNode(args[0]);
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("password","q0");
soapBodyElem2.addTextNode(args[1]);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "/clientLogin");
headers.addHeader("Content-Type", "text/xml");
return soapMessage;
}
/**
* Method used to print the SOAP Response
*
* @return
*/
private static String getAuthToken(SOAPMessage soapResponse)
throws SOAPException, TransformerException {
printResponse(soapResponse);
return soapResponse.getSOAPPart().getChildNodes().item(0).getTextContent();
}
private static void printResponse(SOAPMessage soapResponse)
throws TransformerFactoryConfigurationError,
TransformerConfigurationException, SOAPException,
TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
StreamResult result = new StreamResult(bos);
transformer.transform(sourceContent, result);
System.out.println("\nResponse SOAP Message = " + new String(baos.toByteArray()));
}
public static void doTrustToCertificates() throws NoSuchAlgorithmException,
KeyManagementException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) throws CertificateException {
return;
}
} };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
return false;
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}
@vagner-montenegro
Copy link

Thanks, the method doTrustToCertificates, solve my problem with SSL error on call a SOAP Service.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment