Copyright  2001-2007 Nicholas Quaine.
Home   Basics   ServerSide   ClientSide   Demos   FAQ   Resources
ClientSide
1. Overview
2. Apache SOAP
3. SOAP::Lite
4. MS SOAP
Packages
Version Details
Sun Java
Apache SOAP
Active Perl
SOAP::Lite
MS SOAP Toolkit

Prev   1    2    3    4    Next
Client-Side SOAP
2. Apache SOAP for Java

This section shows you how to write a SOAP client using Apache SOAP for Java. The instructions given here pertain to Win32 and Unix systems but can be adapted for any applicable platform.

Introduction
We will be writing some very simple SOAP clients which will exploit the Quotation Service as described and developed in the Section 4 of Server-Side SOAP. If you have already gone through the Server-Side SOAP tutorial and implemented and tested the Quotation Service then you have already seen these clients. The only difference on this page is that there is a little more explanation of how they tick.

You can incorporate the java code you find here into Java Server Pages, Servlets, Applet-based web pages and stand-alone GUI-based java clients. But it is not our intention to show detailed examples of all of these client types here because the SOAP-related code that you would incorporate is essentially invariant. So we will just look at the bare essentials in a stripped down client with the rawest user interface possible.

As is the case when writing clients to any SOAP service, ensure in advance that you are familiar with the service and its method signatures.

We will build three clients, one for each service method. The source files are available in the soapuser-1.0.zip archive. If you have not already downloaded and extracted this file then save it to your machine and extract to C:\soap [ ~/soap if using Unix ]. Everything will be contained in a subdirectory called soapuser-1.0. In particular the java client source files will be under soapuser-1.0\src in a directory structure that complies with the package name (ie. com\soapuser\soap\client\quotation).

Check your Java Version
In your preferred Java IDE, ensure that you have JDK 1.3.0 or later available. If you have a version prior to 1.3 then you can download Java 1.3 free of charge from Sun Microsystems. Go to http://java.sun.com/j2se/1.3/, choose the download section relevant to your operating system, in the section entitled "Download Java 2 SDK, v 1.3.x Software..." hit CONTINUE, read and ACCEPT the agreement (if you are happy with the terms) then choose the appropriate site for FTP download. Save the file to your machine. This is a self-extracting executable. Run it and follow the instructions to extract the package. You may then need to reconfigure your IDE to take into account the new package.

If you have a version prior to 1.3 and for whatever reason do not want to install 1.3 (even though two Java SDK versions can, in general, be installed in parallel without danger) then feel free to proceed anyway though we cannot guarantee that the tutorial will work for you. Some prior versions will work though it is not our intention to test them all and provide a compatibility list.

Compile the Source Files
To develop using the example source files take the following steps:

  • Create a project in your preferred Java IDE.
  • Ensure that the JDK in use for the project is JDK 1.3.0 or later.
  • Set the project source path to C:\soap\soapuser-1.0\src.
  • Add to the project the three java source files found in the subdirectory com\soapuser\soap\client\quotation.
  • Make the following libraries available to the project. See steps four and five in Server-Side SOAP (Section 3) for details on where to find these packages and how to install them on your machine. Important Note : Ensure with whatever priority scheme that your IDE employs that xerces.jar is before parser.jar on the classpath. Here are the libraries to add [ replace C:\soap with ~/soap if using Unix ]:
    • SOAP : C:\soap\soap-2_2\lib\soap.jar
    • JAVAMAIL : C:\soap\javamail-1.2\mail.jar
    • JAF : C:\soap\jaf-1.0.1\activation.jar
    • XERCES : C:\soap\xerces-1_2_3\xerces.jar
  • Compile the project.
Understanding the Source Files
As a way of explaining how these clients work, here are the instructions for writing a SOAP client using Apache SOAP for Java as delivered in the Apache Documentation itself (instructions in italics), followed by an explanation and/or code snippet from the GetQuotationsByAuthor client to illustrate.
  1. Obtain the interface description of the SOAP service, so that you know what the signatures of the methods that you wish to invoke are.
    // Quotation[] getAllQuotations ( );
    // String[] getQuotationsByAuthor ( String author );
    // void submitQuotation ( String author, String text );
    
  2. Make sure that there are serializers registered for all parameters which you will be sending, and deserializers for all information which you will be receiving back.
    // Standard java types (such as int or String) are handled 
    // automatically. The complex type Quotation is registered 
    // using the following code 
    
    SOAPMappingRegistry smr = new SOAPMappingRegistry();
    BeanSerializer beanSer = new BeanSerializer();
    smr.mapTypes(Constants.NS_URI_SOAP_ENC,
                 new QName("urn:QuotationService", "quotation"),
                 Quotation.class, beanSer, beanSer);
    
  3. Create the org.apache.soap.rpc.RPCMessage.Call object.
    // note that we must also link the SOAPMappingRegistry 
    // object to it and set the encoding style (set here 
    // to the standard SOAP encoding) 
    
    Call call = new Call();
    call.setSOAPMappingRegistry(smr);
    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
    
  4. Set the target URI in the Call object using the setTargetObjectURI(...) method.
    call.setTargetObjectURI("urn:QuotationService");
    
  5. Set the method name that you wish to invoke in the Call object using the setMethodName(...) method.
    call.setMethodName("getQuotationsByAuthor");
    
  6. Create any Parameter objects necessary for the RPC call and set them in the Call object using the setParams(...) method.
    // the parameters are set up in a vector - to send more 
    // than one parameter, just keep doing addElement (as can 
    // be seen in the SubmitQuotation client). 
    
    Vector params = new Vector();
    params.addElement(new Parameter("Author", String.class,
                                    "Wilde, Oscar", null));
    call.setParams(params);
    
  7. Execute the Call object's invoke(...) method and capture the Response object which is returned from invoke(...). The invoke(...) method takes in two parameters, the first is a URL which identifies the endpoint at which the service resides and the second is the value to be placed into the SOAPAction header (can be empty).
    // note that if we catch a SOAPException that means 
    // we had an error client-side (not server-side) 
    
    Response resp;
    try
    {
        resp = call.invoke(
          "http://localhost:8080/soap/servlet/rpcrouter", "");
    }
    catch (SOAPException e)
    {
        System.err.println("Caught SOAPException (" +
          e.getFaultCode() + "): " + e.getMessage());
        return;
    }
    
  8. Check the Response object to see if a fault was generated using the generatedFault() method.
    if (!resp.generatedFault())
    
  9. If a fault was returned, retrieve it using the getFault(...) method, otherwise extract any result or returned parameters using the getReturnValue() and getParams() methods respectively.
    if (!resp.generatedFault())
    {
        Parameter ret = resp.getReturnValue();
        Object value = ret.getValue();
        if ( value != null )
        {
            String[] tlist = (String[])value;
            System.out.println();
            for ( int i = 0; i < tlist.length; i++ )
                System.out.println(tlist[i]);
        }
    }
    else
    {
        Fault fault = resp.getFault();
        System.err.println("Generated fault: ");
        System.out.println ("  Fault Code   = "
    	                    + fault.getFaultCode());
        System.out.println ("  Fault String = "
    	                    + fault.getFaultString());
    }
    
Running the Clients
Below is a script showing you one way to run these clients (you will probably need to alter the classpath entry shown in bold so that it corresponds to the place where your class files are created). Note that the arrow ( ) is used to indicate where a line is a continuation of the preceeding one but we had to split it just for display purposes.
Win32 script : testquotationservice.bat

  set CLASSPATH=C:\soap\soap-2_2\lib\soap.jar
  set CLASSPATH=%CLASSPATH%;C:\soap\javamail-1.2\mail.jar
  set CLASSPATH=%CLASSPATH%;C:\soap\jaf-1.0.1\activation.jar
  set CLASSPATH=%CLASSPATH%;C:\soap\xerces-1_2_3\xerces.jar
  set CLASSPATH=%CLASSPATH%;C:\soap\soapuser-1.0\classes
  java com.soapuser.soap.client.quotation.GetAllQuotations
    http://localhost:8080/soap/servlet/rpcrouter
  java com.soapuser.soap.client.quotation.SubmitQuotation
    http://localhost:8080/soap/servlet/rpcrouter
    "Kennedy, John F." "Forgive your enemies, but never forget their names."
  java com.soapuser.soap.client.quotation.GetQuotationsByAuthor
    http://localhost:8080/soap/servlet/rpcrouter "Wilde, Oscar"
  pause
Unix script : testquotationservice.sh

  #!/bin/sh
  CLASSPATH=~/soap/soap-2_2/lib/soap.jar
  CLASSPATH=${CLASSPATH}:~/soap/javamail-1.2/mail.jar
  CLASSPATH=${CLASSPATH}:~/soap/jaf-1.0.1/activation.jar
  CLASSPATH=${CLASSPATH}:~/soap/xerces-1_2_3/xerces.jar
  CLASSPATH=${CLASSPATH}:~/soap/soapuser-1.0/classes
  export CLASSPATH
  java com.soapuser.soap.client.quotation.GetAllQuotations
    http://localhost:8080/soap/servlet/rpcrouter
  java com.soapuser.soap.client.quotation.SubmitQuotation
    http://localhost:8080/soap/servlet/rpcrouter
    "Kennedy, John F." "Forgive your enemies, but never forget their names."
  java com.soapuser.soap.client.quotation.GetQuotationsByAuthor
    http://localhost:8080/soap/servlet/rpcrouter "Wilde, Oscar"

Note that the script shown here presumes that you have the Quotation Service running on your machine (at localhost:8080). If this is not the case then you can run the clients against our demo SOAP server. To do this simply replace localhost:8080 with services.xmethods.net in the above script. For more information on our demo server, refer to the Demo Section .

Conclusion
Note that there is a lot of detail hardcoded into the client that is a copy of information present in the deployment descriptor. If you have access to the deployment descriptor on the client side then you may want to check out this article on how to simplify the client-side source and avoid such code repetition.

That's all there is to it for clients using Apache SOAP for java. Next we will look at clients written with SOAP::Lite for perl - one of the most elegant SOAP packages out there.

[ Nicholas Quaine ]

Next

Copyright 2001-2007 Nicholas Quaine. All rights reserved.