1)通過WSDL文件生成客戶端調用程序
首先我們通過http://localhost:8080/webservice_helloworld/HelloWorldService.ws?wsdl我們可以獲得WSDL文件HelloWorldService.wsdl,並將其放在src目錄下面,接着我們通過程序訪問該WSDL文件,並調用需測試的方法。此時測試類WebServiceClientTest.java的內容如下所示:
- package test;
- import org.codehaus.xfire.client.Client;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- import webservice.HelloWorld;
- /**
- *Copyright2007GuangZhouAmigo.
- *Allrightreserved.
- *HelloWorld的webservice的測試類.
- *@author<a href="mailto:[email protected]">AmigoXie</a>
- *@version1.0
- *Creationdate:2007-9-16-下午05:36:05
- */
- public class WebServiceClientTest {
- HelloWorld helloWorld = null;
- public static void main(String[] args) throws Exception {
- WebServiceClientTest test = new WebServiceClientTest();
- test.testClient();
- }
- public void testClient() throws Exception {
- String wsdl = "HelloWorldService.wsdl"; //對應的WSDL文件
- Resource resource = new ClassPathResource(wsdl);
- Client client = new Client(resource.getInputStream(), null); //根據WSDL創建客戶實例
- Object[] objArray = new Object[1];
- objArray[0] = "kk";
- //調用特定的Web Service方法
- Object[] results = client.invoke("sayHelloWorld", objArray);
- System.out.println("result: " + results[0]);
- }
- }
運行該類,可得到如下輸出結果:
result: hello,kk
可看出運行結果正確。
2)根據服務地址創建客戶端調用程序
接着讓我們來看一個根據服務地址創建客戶端調用程序的例子。我們可以通過測試類來測試Web Service的正確性,下面讓我們來看一個簡單的測試類,首先我們在src/test目錄建立WebServiceClientTest.java文件,並在src目錄下建立客戶端調用的Spring配置文件client.xml。在client.xml配置文件中我們定義了一個testWebService的bean,該bean訪問wsdlDocumentUrl爲http://localhost:8080/webservice_helloworld/HelloWorldService.ws?wsdl的WSDL。該xml文件的詳細內容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
- "http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
- <bean id="testWebService" class="org.codehaus.xfire.spring.remoting.XFireClientFactoryBean">
- <property name="serviceClass">
- <value>webservice.HelloWorld</value>
- </property>
- <property name="wsdlDocumentUrl">
- <value>http://localhost:8080/webservice_helloworld/HelloWorldService.ws?wsdl</value>
- </property>
- </bean>
- </beans>
在WebServiceClientTest.java文件中獲得HelloWorld,並調用它的sayHelloWorld方法來完成測試,該類的詳細內容如下所示:
- package test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import webservice.HelloWorld;
- /**
- *HelloWorld的webservice的測試類.
- */
- public class WebServiceClientTest {
- HelloWorld helloWorld = null;
- public static void main(String[] args) {
- WebServiceClientTest test = new WebServiceClientTest();
- test.testClient();
- }
- public void testClient() {
- ApplicationContext ctx = new ClassPathXmlApplicationContext(
- "client.xml");
- helloWorld = (HelloWorld) ctx.getBean("testWebService");
- System.out.println(helloWorld.sayHelloWorld("kk"));
- }
- }
在啓動webservice_helloworld工程的情況下,運行WebServiceClientTest類,可看到控制檯包含如下信息:
hello,kk
由此可看出調用Web Service成功。