1. 程式人生 > >WebService實現獲取天氣情況

WebService實現獲取天氣情況

1. WebServices簡介
1.1什麼是WebServices
 WebServices是應用程式元件
      WebServices使用開放協議進行通訊
      WebServices是獨立並可以自我描述
      WebServices可通過使用UDDI來發現
      WebServices可被其它應用程式使用
      XML是WebServices的基礎

1.2工作模式
XML+HTTP

1.3WebServices平臺元素
 SOAP(簡單物件訪問協議)
   UDDI(它是一種目錄服務)
   WSDL(Web services描述語言)

2. 為什麼使用WebServices 可在不同的應用程式與平臺之間交換資料
 
3.實現天氣預報
開啟http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl 你會看到

使用記事本將齊開啟將<s:element ref="s:schema" />  
全部刪除掉不然在生成java檔案的時候會報錯

然後開啟cmd視窗使用cd命令跳轉到該路徑(獲取直接在下載路徑shirt+右鍵點選選擇直接在此處開啟命令視窗)

然後執行wsimport -keep *.xml命令會在當前路徑下生成一個cn資料夾裡面就是java程式碼

然後我們寫一個類來獲取天氣資訊:

package cn.com.weather;
 
import java.util.List;
 
import cn.com.webxml.ArrayOfString;
import cn.com.webxml.WeatherWS;
import cn.com.webxml.WeatherWSSoap;
 
public class Weather {
 
	/**
	 * 獲取城市資訊
	 * 
	 * @param cityname    城市名
	 *        
	 */
	public void getWeather(String cityname) {
		// 建立例項化物件
		WeatherWS weatherWS = new WeatherWS();
		// 通過例項化物件建立介面
		WeatherWSSoap weatherWSSoap = weatherWS.getWeatherWSSoap();
		// 通過介面傳入城市名獲取天氣資訊
		ArrayOfString weather = weatherWSSoap.getWeather(cityname, null);
		if (weather != null) {
			// 將獲取到的資訊轉成集合然後遍歷
			List<String> weathers = weather.getString();
			weathers.forEach(s -> System.out.println(s));
		}
 
	}
 
}

然後測試:

package cn.com.test;
 
import cn.com.weather.Weather;
/**
 *測試類
 * @author Administrator
 *
 */
public class Test {
public static void main(String[] args) {
	Weather weather=new Weather();
	weather.getWeather("長沙");
}
}

測試結果:

本文轉載自:https://blog.csdn.net/yjt520557/article/details/84883695