承接上篇(服務端發布),本教程示範如何利用 Eclipse IDE、Java SE 6 內建 wsimport、Ant 腳本生成客戶端代碼、撰寫調用邏輯、命令列部署運行,並以 TCP/IP Monitor 捕獲 SOAP 訊息雙向流向。
wsClientExample,關聯 Java SE 6 JRE。com.myfirst.wsClient。build.xml 呼叫 wsimport:<project default="wsimport">
<target name="wsimport">
<exec executable="${java.home}/../bin/wsimport">
<arg line="-keep -s ./src -p com.myfirst.wsClient -d ./bin
https://localhost:8080/wsServerExample?wsdl"/>
</exec>
</target>
</project>
RunService(服務端發布 WSDL)。build.xml → Run As → Ant Build,Console 顯示 BUILD SUCCESSFUL。com.myfirst.wsClient 下出現 JAX-WS 可攜式工件(Service、Port、請求/回應 Bean 等)。關鍵區別:wsgen 讀取端點類生成部署工件(服務端);wsimport 讀取 WSDL 生成開發/調用工件(客戶端)。
package com.myfirst.wsClient;
import javax.xml.ws.BindingProvider;
public class SayHelloClient {
public static void main(String[] args) {
SayHelloService shs = new SayHelloService();
SayHello sh = (SayHello) shs.getSayHelloPort();
// 設定端點位址(若 WSDL 中位址非預期)
((BindingProvider)sh).getRequestContext().put(
BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"https://localhost:8080/wsServerExample");
System.out.println(sh.getGreeting("Fiona")); // 輸出: Hello Fiona
}
}
Eclipse 右鍵 Run As → Java Application 即可見結果。進階版加入互動迴圈:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName;
while (!(userName = br.readLine()).equalsIgnoreCase("quit")) {
System.out.println(sh.getGreeting(userName));
}
修改 build.xml 新增 runServer、pause、runClient 目標,spawn="true" 於獨立命令視窗啟動:
<target name="runServer">
<exec dir="${java.home}/bin/" executable="cmd" spawn="true" os="Windows XP">
<arg line="start cmd /K java -cp "${basedir}/../wsServerExample/bin" com.myfirst.wsServer.RunService"/>
</exec>
<exec executable="xterm" spawn="true" os="Linux"> ... </exec>
</target>
<target name="pause" depends="runServer"><sleep seconds="5"/></target>
<target name="runClient" depends="pause"> ... </target>
執行 Ant Build,雙視窗並行,客戶端持續提示輸入姓名,服務端回應問候,輸入 quit 雙雙退出。
https://localhost:8081/wsServerExample(經 Monitor 轉發)。請求:
POST /wsServerExample HTTP/1.1
SOAPAction: ""
Content-Type: text/xml; charset=utf-8
...
<S:Envelope xmlns:S="https://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getGreeting xmlns:ns2="https://wsServer.myfirst.com/">
<arg0>Fiona</arg0>
</ns2:getGreeting>
</S:Body>
</S:Envelope>
回應:
HTTP/1.1 200 OK
Content-type: text/xml; charset=utf-8
Transfer-encoding: chunked
...
<S:Envelope ...>
<S:Body>
<ns2:getGreetingResponse ...>
<return>Hello Fiona</return>
</ns2:getGreetingResponse>
</S:Body>
</S:Envelope>
Envelope → Body → 具體操作元素,清晰對應 Java 方法調用。可選 WS-I 合規性驗證(紅圈圖標)導出日誌離線分析。
Java SE 6 + Eclipse 讓獨立 Web Service 開發部署輕量化,無需重型應用伺服器,適合輕量級整合、微服務原型、教學演示等場景。