Example SOAP client code.

Java To Go!
SOAP-enabling business-to-business EJB
E-Ming Tan
Listing 4. Example SOAP client code.


public class SOAPClient {
  public static void main (String[] args) throws Exception {
    if (args.length != 4
        && (args.length != 5 || !args[0].startsWith (“-“))) {
      System.err.println (“Usage: java “ + SOAPClient.class.getName () +
                          “ [-encodingStyleURI] SOAP-router-URL id xmldata
                                                                   xpath”);
      System.exit (1);
    }

    // Process the arguments.
    int offset = 5 - args.length;
    String encodingStyleURI = args.length == 5
                          ? args[0].substring(1)
                          : Constants.NS_URI_SOAP_ENC;
  URL url = new URL (args[1 - offset]);
  String id = args[2 - offset];
  String xmldata = args[3 - offset];
  String xpath = args[4 - offset];

  System.out.println(“SOAP url : ‘” + url + “’”);
  System.out.println(“SOAP id : ‘” + id + “’”);
  System.out.println(“SOAP xmldata : ‘” + xmldata + “’”);
  System.out.println(“SOAP xpath : ‘” + xpath + “’”);

  // Build the call.
  Call call = new Call ();
  call.setTargetObjectURI (“urn:SOAP-xmlbean-xmldata”);
  call.setMethodName (“getXMLData”);
  call.setEncodingStyleURI(encodingStyleURI);
  Vector params = new Vector ();

  params.addElement (new Parameter(“id”, Integer.class, id, null));
  params.addElement (new Parameter(“xmldata”, String.class, xml
                                                   data, null));
  params.addElement (new Parameter(“xpath”, String.class, xpath,
                                                          null));

  call.setParams (params);

  // make the call: note that the action URI is empty because the
  // IBM-SOAP rpc router does not need this. This may change in the
  // future.
  Response resp = call.invoke (/* router URL / url, / actionURI */ “”);

 // Check the response.
  if (resp.generatedFault ()) {
    Fault fault = resp.getFault ();
    System.out.println (“Ouch, the call failed: “);
    System.out.println (“ Fault Code = “ + fault.getFaultCode ());
    System.out.println (“ Fault String = “ + fault.getFaultString ());
  	} else {
    Parameter result = resp.getReturnValue ();
    System.out.println (result.getValue ());
   }
 }
}