建立 Web Service Client
作業環境:Windows XP SP3
軟體版本:
- Eclipse v3.4.1
說明:要使用 Eclipse 來建立一個 Web Service Client 來取用 Web Service。
版本更新
- 2009.2.22 新增此頁面
大綱
- 1. 取得 Web Service
- 2. 建立測試 Client Class
- 3. 相關資源
- 3.1. Eclipse 專案檔下載
取得 Web Service
- 首先要先建立「Java Project」 可以參考建立 Java 專案這篇文章
- 在「專案名稱」按滑鼠右鍵選擇「New」>「Other...」
- 選擇「Web Services」>「Web Service Client」
- 首先先設定「Service definition」點選「Browse...」
- 將「Web Service 的 URI」填上,這邊院長介紹一個 Web Service 的搜尋引擎 seekda.com 可以搜尋需要的 Web Service,這邊採用的 Web Service 是 aspalliance.com 所提供的 MathService 這個 Web Service 提供很簡單的加、減、乘、除的數學計算。
這邊的「WSDL File」就是 Web Service 最重要的描述檔,下一個步驟就是要從 WSDL 的資訊產生 Web Service Client,另外「Use Now」會簡述這個 Web Service 提供那些方法可供使用。 - 複製 aspalliance.com的 WSDL 連結到 Eclipse 裡面,Eclipse 會抓取 WSDL 檔,按下「OK」就會回到設定的視窗。
- 確認「Service definition」已自動帶入後,就可以按下「Finish」
- 這時 Eclipse 就會自動產生需要的原始碼。
建立測試 Client Class
- 在「src」中「New」一個「Class」
- 填上「Package」與「Name」,並且勾選建立「main」函式。
- 將「Client」的原始碼補上,初始化 MathServiceSoapProxy 物件,接下來就可以使用物件的方法,這邊院長是測試一個加法的方法。
01
package
tw.cheyingwu.ws;
02
03
import
java.rmi.RemoteException;
04
05
import
org.tempuri.*;
06
07
public
class
WSDemo {
08
09
public
static
void
main(String[] args)
throws
RemoteException {
10
MathServiceSoap ms =
new
MathServiceSoapProxy();
11
System.out.println(ms.add((
float
)
0.3
, (
float
)
0.4
));
12
}
13
14
}
- 測試 Web Client 選擇「Run」>「Run As」>「Java Application」
- 執行後 Web Service Client 就會將參數傳到遠端的 Web Service 並取得回傳的計算結果。
相關資源
Eclipse 專案檔下載
這裡有提供本次教學的專案檔,下載後匯入 Eclipse 就可以執行本教學專案。
转载出处:http://wiki.cheyingwu.tw/Eclipse/Web_Service_Client#