Tuesday, March 17, 2015

Creating a web service client using apache Cxf

In this tutorial you will see how to create a web service client(synchronous) using apache Cxf.
First download the apache cxf  binary distribution from cxf download page.
http://cxf.apache.org/download.html
Extract the downloaded archieve and it will create a folder named like apache-cxf-x.x.x.

Now create a new Java project. I name it as CXFClient.
In this tutorial I am going to write a client to consume cdyne.com's Weather service.
This is the WSDL for that service.
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

Now you can create the stub for the above web service as below.
Open command window and point to apache-cxf-x.x.x\bin.
Below command will generate the stub for the above web service in to a folder named mystub inside bin folder.

wsdl2java -ant -client -p com.example.stub -d mystub http://wsf.cdyne.com/Weather.asmx?WSDL

You will see the stub is generated inside the apache-cxf-x.x.x\bin\mystub folder. Open the stub folder and copy the content in to the src(java source) folder of your project.
Now I am going to create my client class to consume the web service. Create a new java class in com.example.client package and name it as WeatherClient.

If you are using eclipse, your project structure will look like this now.


























This is my client class to invoke the weather service. Run this class and you will see the the data is retrieved through the web service.
package com.example.client;

import java.util.List;
import com.example.stub.ArrayOfWeatherDescription;
import com.example.stub.Weather;
import com.example.stub.WeatherDescription;
import com.example.stub.WeatherSoap;

public class WeatherClient {
  public static void main(String[] args) {
    try {
      Weather weatherService = new Weather();
      WeatherSoap weatherSoap = weatherService.getWeatherSoap();
      ArrayOfWeatherDescription forecastReturn = weatherSoap.getWeatherInformation();
      List forecasts = forecastReturn.getWeatherDescription();
      for (WeatherDescription forecast : forecasts) {
        short weatherID = forecast.getWeatherID();
        String description = forecast.getDescription();
        System.out.println("weatherID : " + weatherID);
        System.out.println("description : " + description);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

No comments:

Post a Comment