Web Services Tidbit
Today I thought I'd share a little trick with respect to simple web services.
As you may or may not know, the basis of a web serivice is an xml message (SOAP message) transmitted over http. That same protocol used by your web pages.
Now keeping this in mind, its possible to call a web service using the http API's within Java.
Below is a simple Java program to call a web service that was previously created using Java CAPS (Although any simple web service will do). It uses HTTP to communicate with the web service and sends a static SOAP envelope and displays the reply.
package soaptest;
import java.io.*;
import java.net.*;
public class SOAPTester {
public static String invokeWS(String SOAPUrl, String payload, String SOAPAction) throws Exception {
StringBuffer response = new StringBuffer();
byte[] b = payload.getBytes();
// Create the connection where we're going to send the file.
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = null;
boolean error = false;
IOException ioe = null;
try {
isr = new InputStreamReader(httpConn.getInputStream());
} catch (IOException e) {
e.printStackTrace();
error = true;
ioe = e;
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
if (error) throw new Exception(response.toString(), ioe);
return response.toString();
}
public static void main(String[] args){
try{
// The URL is taken from the WSDL. Its from the location of the port.
String URL = "http://localhost:18001/Sandpit_RequestReply__u002F_SimpleWebServicedpSimpleWebService/PortTypeBndPort";
// I cheated and took the envelope from SOAPUI.
String data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://TM5-HPaffrath:12000/repository/HJP_JCAPS512/xsd/Correlation/HJP_JCAPS512112ce48:116c1d23c96:-7fff/XSDDefinition1\">" +
"<soapenv:Header/>" +
"<soapenv:Body>" +
"<xsd:Message>" +
"<MessageID>23456</MessageID>" +
"<Date>2007-12-28</Date>" +
"<Payload>Hello World</Payload>" +
"</xsd:Message>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
System.out.println("Result = [" + invokeWS(URL,data,"") + "]");
} catch (Exception e){
e.printStackTrace();
}
}
}
Posted at 09:56PM Jan 19, 2008 by Holger Paffrath in Sun | Comments[0]
