Thursday, August 7, 2014

JAX-WS Web Service Client for Java

This post will show you how to generate Web Service Client in Java and how to invoke the Web Service using the generated client.

To generate web service client we will use wsimport tool that comes with jdk. you can find the tool in JAVA_HOME/bin directory of your machines.

You will need wsdl file for this. If you have a url of wsdl then you can directly use that. Alternatively you can save the wsdl file on your local machine too.

Use below command to generate the java code for the client.

wsimport -keep <wsdl_path>

e.g. wsimport -keep "http://www.abc.com/MyService?WSDL" 
       wsimport -keep "c:/abc/xyz/mywsdl.wsdl"

-keep option will keep the generated java source files along with class files.

If webservice has additional headers to be passed , then use below command, to generate parameterized method for headers. In this you can pass header directly while invoking the web service methods rather than writing separate handlers for that.

wsimport -keep -XadditionalHeaders <wsdl_path>

This will generate the required java files into the current directory.

Invoking webservice using the generated client

Although you can run the client as a standalone java program without using any IDE, but it would be good if you use eclipse to run this.

Create a new "Java Project" in eclipse. copy all the files generated in src directory of your java project along with directory structure.

Lets consider the servicename as 'TestService' . So based on this service name, wsimport should have generated below 2 java files along with others.

TestServiceService.java

TestService.java

You can invoke your webservice using the below code snippet.
For this you can create a test class in your test project with main method. you can call the below code in your main method.

TestServiceService serviceImpl = new TestServiceService();
Testservice testservice = serviceImpl.getTestServicePort();

-- you can invoke any of the webservice method now.. like

testservice.test1();

Printing SOAP requests sent from SOAP client and responses received from SOAP services and formatting it.


To print and format SOAP messages you can refer to this post : Printing SOAP request/response messages while invoking web services in Java

No comments:

Post a Comment

Creating and Deploying Java Web Application on AWS using Elastic Beanstalk

This tutorial is for creating simple java web application using eclipse and then deploying it on AWS cloud. Video tutorial for creating/de...