Simplest Soap Example

Simplest SOAP example

This is the simplest JavaScript SOAP Client I can create.

<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://somesoapurl.com/', true);

// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soapenv:Body>' +
'<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<username xsi:type="xsd:string">login_username</username>' +
'<password xsi:type="xsd:string">password</password>' +
'</api:some_api_call>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';

xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
// alert('done. use firebug/console to see network response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html> <!-- typo -->

Working Soap client example

To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above, but removed again in Java 11):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity

To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action

Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

callSoapWebService(soapEndpointUrl, soapAction);
}

private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();

String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";

// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/

// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}

private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();

// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();

soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}

private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();

createSoapEnvelope(soapMessage);

MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);

soapMessage.saveChanges();

/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");

return soapMessage;
}

}

How can I send a SOAP request and receive a response using HTML?

Well, a SOAP server is designed to receive SOAP requests and send SOAP responses.

Since SOAP is basically XML, instead of expecting an HTML response from the server, it would be more appropriate to look for a mean to parse the XML of the SOAP response and display it in HTML.

But as I'm typing this answer, I think you may have misunderstood the goal of a SOAP server. It seems to me that you want to display the raw SOAP response directly to the client browser. But a SOAP server is not intended to work that way.

Typically a SOAP server is used by another server, by doing a SOAP request to it and then parsing the SOAP response. And this "other server" may be, for example, an HTTP server.

Let's take an example. I want to know the weather forecast of my city for tomorrow. I go to dummyweatherforecast.com and type the name of my city in the search field. But dummyweatherforecast.com does not store all the weather forecasts by itself. It may instead contact a SOAP server (specifically designed to provide weather forecasts) with a SOAP request containing the name of my city. The SOAP server returns a SOAP response with different weather information (sunny/cloudy, temperature, etc.) and then dummyweatherforecast.com processes this SOAP response (that is, as a reminder, XML) to display it to the client with a beautiful sentence like "It will be sunny tomorrow, with 86°F. Take your swimsuit !" ornamented with a beautiful sun iconography.

As you see, the client doesn't even know that a SOAP communication is held between dummyweatherforecast.com and the SOAP server. And this how SOAP is used : by servers themselves, and rarely directly by clients. This is what we call "web services", even though this term refers to a more general set of technologies used to make computers talk to each others.

I hope this brightened your mind a little bit.

PS : by the way, the link you give for your server points to an IP not available publicly (192.168 adresses are for private networks).

How to call SOAP WS from Javascript/jQuery

You cannot send cross domain AJAX requests because of the same origin policy restriction that's built into the browsers. In order to make this work your HTML page containing the jQuery code must be hosted on the same domain as the Web Service (http://192.168.1.5/ws/MyWS/).

There are workarounds that involve using JSONP on the server, but since your web service is SOAP this cannot work.

The only reliable way to make this work if you cannot move your javascript on the same domain as the web service is to build a server side script that will be hosted on the same domain as the javascript code and that will act as a bridge between the 2 domains. So you would send an AJAX request to your server side script which in turn will invoke the remote web service and return the result.



Related Topics



Leave a reply



Submit