Friday, May 23, 2008

XML Web service – Simple Axis2 client

Axis2 is a core engine for webservice, providing APIs for generating webservices and clients, it can also function as a standalone server application.

Axis2 clients has more advantages over other clients generated by other tools;
- Enables to dynamically assign wsdl url at runtime when invoking client. (as will be mentioned later on)
- Code generated by IDEs is usually hard to trace / resolve raised error. (My personal view, i suffered a lot to resolve errors raised by RAD 6 generated clients, and couldn't get clear solution till now..)

(A) We're going to see how to generate client stub for webservice mentioned in the previous post. But first you have to configure system to use Axis2 commands:

- download axis2 binary distribution
- download Apache ant
- unzip axis2-bin to any location in the file system; say C:/axis2-bin
- set the following environment variables:
JAVA_HOME: java installation directory (…/Java/jdk1.6.x)
AXIS2_HOME: axis2-bin directory (C:/axis2-bin)
PATH: bin directory under axis2 location and bin directory under ant installation ($AXIS2_HOME/bin; ….ant-installation/bin)

(B) Now you can generate client code using the following command:

wsdl2java -uri wsdl_uri -o output_folder

wsdl_uri: example webservice wsdl of the previous example (http://localhost:8080/service/services/MainService?wsdl)

output_folder: folder where code is generated (C:/client)

you have the following resources generated in the file system:
- C:/client/src/…… (source code .java files)
- C:/client/ resources
- C:/client/build.xml (to generate client jars using ant)

(C) in the command line go to the generated client directory (C:/client), then type: ant
(this will generate jar files under C:/client/dist to be included in any client app)

(D) To invoke webservice in your client, add generated client jars under C:/client/dist/.. to the your application classpath, then add axis2 jars to classpath. (axis2 jars found under AXIS2_HOME/lib)
Here's a code snippet to invoke sayHi method of the webservice:

MainServiceStub stub = new MainServiceStub();
WSMainServiceStub.SayHi sayHi = new WSMainServiceStub.SayHi();
sayHi.setName("client");
WSMainServiceStub.SayHiResponse response = stub.sayHi(sayHi);
System.out.println(response.getSayHiReturn());

To dynamically refer to wsdl url at runtime, you replace the default constructor with another one referring to wsdl url, example:

String url=
"http://localhost:8080/service/services/MainService?wsdl";
MainServiceStub stub = new MainServiceStub(url);


This makes your client more portable.
Next I'm going to show you how to invoke webservice method with complex data types,
using xml data binding.

1 comment:

Anonymous said...

Good fill someone in on and this mail helped me alot in my college assignement. Say thank you you seeking your information.