Tuesday, March 19, 2013

Web Service Client in Java Using JAX-WS

This tutorial describes how to consume a SOAP web service in Java using JAX-WS. For this tutorial, we'll create a client application that makes a call to a SOAP service hosted on wsf.cdyne.com.

  1. The first step is to import the WSDL of the web service to create the client proxy code. From the command prompt, navigate to the directory where you want to generate the client code and type: "wsimport -s . http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL". After running this command, you'll find a \com\cdyne\ws\weatherws directory has been created with a number of .java and .class files.


  2.  
  3.  Next, we'll write a simple Java class and main method to invoke the web service.
  4.   public class WeatherTest {
      
        public static void main(String args[]) {
            Weather weather = new Weather();
          
            WeatherSoap weatherSoap = weather.getWeatherSoap();
          
            ForecastReturn forecastReturn = weatherSoap.getCityForecastByZIP("56701");
          
            ArrayOfForecast arrayOfForecast = forecastReturn.getForecastResult();
            List<Forecast> forecasts = arrayOfForecast.getForecast();
          
            for (Forecast forecast : forecasts) {
                System.out.println(forecast.getDate().toString() + " " + forecast.getDesciption());
            }
        }

    }


  5. The output from this program is:
    2013-03-14T00:00:00 Mostly Cloudy
    2013-03-15T00:00:00 Snow
    2013-03-16T00:00:00 Partly Cloudy
    2013-03-17T00:00:00 Partly Cloudy
    2013-03-18T00:00:00 Snow
    2013-03-19T00:00:00 Partly Cloudy
    2013-03-20T00:00:00 Partly Cloudy

No comments:

Post a Comment