1. 程式人生 > >webservice通訊呼叫天氣預報介面例項

webservice通訊呼叫天氣預報介面例項

一:環境搭建

1:新建一個java project工程weatherInf

2:引入相應的jar包

activation.jar
axis-ant.jar
axis.jar
commons-discovery-0.2.jar
commons-logging-1.0.4.jar
jaxrpc.jar
log4j-1.2.8.jar
mail.jar
saaj.jar
wsdl4j-1.5.1.jar

下載axis 1.4 src壓縮包,解壓後到webapp/web-info/lib下取包,具體路徑如下:

http://download.csdn.net/detail/yyg64/5351114

其中mail.jar 以及 activation.jar 可到如下路徑下載:

http://download.csdn.net/detail/dbhunter/398258

3:將天氣預報介面wsdl檔案拷貝到src目錄下

http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl

二:目錄結構

三:根據wsdl檔案生成客戶端程式碼

wsdl檔案——右鍵——web services——Generate Client,然後一路next到finish。

會生成如下客戶端程式碼:

四:測試程式碼

複製程式碼
 1 /**
 2  * 
 3  */
 4 package com.paic.services;
5 6 import java.rmi.RemoteException; 7 8 import javax.xml.rpc.ServiceException; 9 10 import cn.com.WebXml.WeatherWebServiceLocator; 11 import cn.com.WebXml.WeatherWebServiceSoapStub; 12 13 /** 14 * @author Administrator 15 * 16 */ 17 public class TestWeather { 18 public static void main(String[] args) throws
ServiceException, 19 RemoteException { 20 WeatherWebServiceLocator locator = new WeatherWebServiceLocator(); 21 WeatherWebServiceSoapStub service = (WeatherWebServiceSoapStub) locator 22 .getPort(WeatherWebServiceSoapStub.class); 23 invokeGetSupportProvince(service); 24 System.out.println("..................."); 25 invokeGetSupportCity(service); 26 invokeGetWeatherByOneCity(service); 27 } 28 29 // 呼叫獲取支援的省份、州介面 30 public static void invokeGetSupportProvince( 31 WeatherWebServiceSoapStub service) throws RemoteException { 32 String[] provices = service.getSupportProvince(); 33 System.out.println("總共" + provices.length + "個"); 34 int count = 0; 35 for (String str : provices) { 36 if (0 != count && count % 5 == 0) { 37 System.out.println(); 38 } 39 System.out.print(str + "\t"); 40 count++; 41 } 42 } 43 44 // 呼叫獲取支援查詢某個省份內的城市介面 45 public static void invokeGetSupportCity(WeatherWebServiceSoapStub service) 46 throws RemoteException { 47 String provinceName = "江蘇"; 48 String[] cities = service.getSupportCity(provinceName); 49 System.out.println("總共" + cities.length + "個市"); 50 for (int i = 0; i < cities.length; i++) { 51 if (0 != i && i % 5 == 0) { 52 System.out.println(); 53 } 54 System.out.print(cities[i] + "\t"); 55 } 56 } 57 58 // 呼叫查詢某個城市天氣的介面 59 public static void invokeGetWeatherByOneCity( 60 WeatherWebServiceSoapStub service) throws RemoteException { 61 String cityName = "南京"; 62 String[] weatherInfo = service.getWeatherbyCityName(cityName); 63 for (String str : weatherInfo) { 64 System.out.println(str); 65 } 66 } 67 }
複製程式碼

五:得到結果