Friday, February 24, 2012

Dynamic Web Service Client

In Apache Axis2, the are several ways to write a client for a web service. One approach would be to use WSDL2Java, the code generation tool provided with Axis2 generate a stub for the web service and use that stub to consume the web service. Other option is to write a dynamic client. This is how you can write a dynamic client for a web service.

We will you expose a simple POJO as a web service.

  1. package org.wso2.training;  
  2.   
  3. public class CalculatorService {  
  4.     
  5.    public int add (int a, int b) {  
  6.        return a + b;  
  7.    }  
  8.     
  9.    public int multiply(int a, int b) {  
  10.        return a * b;  
  11.    }  
  12.     
  13. }  
Exposing this as a web service is a matter of 2 lines of code ...
  1. AxisServer axisServer = new AxisServer();  
  2. axisServer.deployService(CalculatorService.class.getName());  
Now, the WSDL for this web service will be available at
  1. http://localhost:6060/axis2/services/CalculatorService?wsdl  
Now let's see how we can write a dynamic client for this web service
  1.         //Create a service client for given WSDL service by passing the following four parameters  
  2.         //ConfigurationContext - we keep it as null  
  3.         //wsdlURL - The URL of the WSDL document to read  
  4.         //wsdlServiceName The QName of the WSDL service in the WSDL document   
  5.         //portName        The name of the WSDL 1.1 port to create a client for.   
  6.           
  7.         RPCServiceClient dynamicClient = new RPCServiceClient(nullnew URL(  
  8.                 "http://localhost:6060/axis2/services/CalculatorService?wsdl"), new QName(  
  9.                 "http://training.wso2.org""CalculatorService"),  
  10.                 "CalculatorServiceHttpSoap12Endpoint");  
  11.   
  12.         // We provide the parameters as an object array and return types as an class array  
  13.         Object[] returnArray = dynamicClient.invokeBlocking(new QName("http://training.wso2.org","add"),  
  14.                 new Object[] { 12 }, new Class[] { Integer.class });  
  15.           
  16.         System.out.println("1 + 2 = " + returnArray[0]);  
  17.           
  18.         returnArray = dynamicClient.invokeBlocking(new QName("http://training.wso2.org","multiply"),  
  19.                 new Object[] { 12 }, new Class[] { Integer.class });  
  20.           
  21.         System.out.println("1 X 2 = " + returnArray[0]);  
  22.   
  23. .  

No comments:

Post a Comment