Skip to main content

Part 3

How SOAP works

Return to article


Listing 7. Code for Client2.java

import java.net.*;
import java.util.*;
import org.apache.soap.*; // Body, Envelope, Fault, Header
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.encoding.soapenc.BeanSerializer;
import org.apache.soap.rpc.*; // Call, Parameter, Response
import org.apache.soap.util.xml.QName;

public class Client2
 {
 public static void main( String[] args ) throws Exception
 {
 URL url = new URL( "http://localhost:8070/soap/servlet/rpcrouter" );
 String urn = "urn:demo2:purchasing";

 // prepare the mapping registry
 SOAPMappingRegistry registry = new SOAPMappingRegistry();
 QName qname = new QName( "urn:my_encoding", "Invoice" );
 BeanSerializer serializer = new BeanSerializer();
 registry.mapTypes( Constants.NS_URI_SOAP_ENC, qname, Invoice.class, serializer, serializer );

 // prepare the service invocation
 Call call = new Call();
 call.setSOAPMappingRegistry( registry );
 call.setTargetObjectURI( urn );
 call.setMethodName( "receive" );
 call.setEncodingStyleURI( Constants.NS_URI_SOAP_ENC );
 Vector params = new Vector();
 params.addElement( new Parameter( "invoice", Invoice.class, new Invoice( "MyInvoice", 42 ), null ) );
 call.setParams( params );

 try
 {
 System.out.println( "invoke service\n" + " URL= " + url + "\n URN= " + urn );
 Response response = call.invoke( url, "" ); // invoke the service

 if( !response.generatedFault() )
 {
 Parameter result = response.getReturnValue(); // response was OK
 System.out.println( "Result= " + result.getValue() );
 }
 else
 {
 Fault f = response.getFault(); // an error occurred
 System.err.println( "Fault= " + f.getFaultCode() + ", " + f.getFaultString() );
 }
 }
 catch( SOAPException e ) // call could not be sent properly
 {
 System.err.println( "SOAPException= " + e.getFaultCode() + ", " + e.getMessage() );
 }
 }
 }

Return to article