Teach you how to use Java to call WebService, you need specific code examples
Web service is a software system that communicates through the network, providing services based on XML and standards Remote calling via HTTP protocol. During the development process, we often need to use Java programs to call Web services. This article will teach you how to use Java code to call WebService methods and provide specific code examples.
Save the WSDL file to the src directory of the project. Then, switch to the project's src directory via the command line and use the wsimport tool to generate Java code. The command is as follows:
wsimport -keep -verbose <wsdl_url>
where wsdl_url
is the path or URL of the WSDL file. After executing this command, some Java files will be generated, including interfaces, entity classes, etc. related to web services.
Create a class in the Java project for calling the Web service. First, import the relevant packages:
import com.example.weather.Weather; import com.example.weather.WeatherService;
Before calling the Web service, we first create a WeatherService object. This object is obtained from the generated Java code and corresponds to the definition in the Web service's WSDL file.
WeatherService weatherService = new WeatherService();
Get the Weather interface through the WeatherService object and create a Weather object:
Weather weather = weatherService.getWeatherPort();
Call the method of the Weather object to use the Web service. Depending on the definition of the web service, there may be different methods to call. In this example, we call the getWeatherByCity
method to query the weather in a certain city:
String city = "北京"; String weatherInfo = weather.getWeatherByCity(city);
Here, the getWeatherByCity
method receives a city name as a parameter and returns the city weather information.
Print query results:
System.out.println("城市:" + city); System.out.println("天气:" + weatherInfo);
The above are the basic steps and sample code for calling WebService using Java. By studying this example, you can master how to call any web service using Java. In actual development, you can call different Web services to complete various functions according to specific needs.
It should be noted that the specific calling method of each Web service may be different, but the general steps are similar. The focus is on understanding the WSDL file of the Web service and generating relevant Java code based on it.
The above is the detailed content of Steps to learn how to call WebService using Java. For more information, please follow other related articles on the PHP Chinese website!