Tuesday, November 04, 2008

How to write a dynamic client for a web service in Apache Axis 2

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.

package org.wso2.training;

public class CalculatorService {

public int add (int a, int b) {
return a + b;
}

public int multiply(int a, int b) {
return a * b;
}

}
Exposing this as a web service is a matter of 2 lines of code ...

AxisServer axisServer = new AxisServer();
axisServer.deployService(CalculatorService.class.getName());

Now, the WSDL for this web service will be available at

http://localhost:6060/axis2/services/CalculatorService?wsdl
Now let's see how we can write a dynamic client for this web service

//Create a service client for given WSDL service by passing the following four parameters
//ConfigurationContext - we keep it as null
//wsdlURL - The URL of the WSDL document to read
//wsdlServiceName The QName of the WSDL service in the WSDL document
//portName The name of the WSDL 1.1 port to create a client for.

RPCServiceClient dynamicClient = new RPCServiceClient(null, new URL(
"http://localhost:6060/axis2/services/CalculatorService?wsdl"), new QName(
"http://training.wso2.org", "CalculatorService"),
"CalculatorServiceHttpSoap12Endpoint");

// We provide the parameters as an object array and return types as an class array
Object[] returnArray = dynamicClient.invokeBlocking(new QName("http://training.wso2.org","add"),
new Object[] { 1, 2 }, new Class[] { Integer.class });

System.out.println("1 + 2 = " + returnArray[0]);

returnArray = dynamicClient.invokeBlocking(new QName("http://training.wso2.org","multiply"),
new Object[] { 1, 2 }, new Class[] { Integer.class });

System.out.println("1 X 2 = " + returnArray[0]);

.