本文簡單舉例說明如何使用wsimport工具和JAX-WS API調用Web Service接口。
此方法的優勢:使用JDK自帶的工具和API接口,無需依賴第三方庫。html
JDK版本:1.8.0_141
開發工具:Eclipsejava
1. 使用JDK自帶的wsimport工具根據WSDL生成web service client stub
1.1. 確保已安裝JDK1.6版本或更高版本
1.2. 確保WebService服務已經啓動
1.3. 在命令行運行以下命令:服務器
參數說明:
-d 指定生成輸出文件的保存路徑(.class文件,根據須要決定是否生成class文件)
-s 指定生成的java源文件的保存路徑(.java文件,根據須要決定是否生成java源文件)
-p 指定生成的java類的包(package)名稱
http://localhost:8888/HelloService表示WebService URL地址,URL地址後面必須添加「?WSDL」參數。WSDL參數也能夠是小寫(wsdl)。
要查看服務具體提供了哪些操做,請在URL後面添加「?Tester」參數。(有時候傳遞Tester並不必定能返回結果。這和服務的發佈方式有關)
1.4. 查看生成的文件
如圖所示,輸出的文件保存在按指定的包名稱構成的路徑中(jaxws\client\stub)。
2. 把生成的client stub類導入到eclipse工程中。
網絡
3. 編寫客戶端代碼
建立jaxws.client. HelloAppClient類。
客戶端代碼入下所示: eclipse
package jaxws.client; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import jaxws.client.stub.HelloService; public class HelloAppClient { public static void main(String[] args) { sayHello(); } public static void sayHello() { URL url = null; try { url = new URL("http://localhost:8888/HelloService"); } catch (MalformedURLException e) { e.printStackTrace(); } Service s = Service.create(url, new QName("http://service.jaxws/", "HelloServiceService")); HelloService hs = s.getPort(new QName("http://service.jaxws/", "HelloServicePort"), HelloService.class); String helloMessage = hs.sayHello("Tom"); System.out.println(helloMessage); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }
注意:WebService中所說的Port和網絡端口(port)不是一個概念。
如下WSDL文檔中的一些簡單的概念解釋(若是想深刻了解請查看WSDL標準):工具
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:開發工具
代碼說明:
(1)url表示WebService服務地址。此地址後面能夠添加也能夠不添加「?WSDL」參數。
(2)Service提供WebService服務的客戶端視圖(client view)。它做爲endpoint的客戶端代理,用於分發(dispatch)對遠程Service操做(Operation)的調用(通俗的說就是把某個Service上的方法調用發送給遠程服務器上提供服務的那個Service)。
(3)HelloService表示WebService服務client stub(相似於WebService服務在客戶端的一個鏡像,供客戶端代碼調用其接口)。
(4)經過hs.sayHello方法調用服務接口。url