上一張我們講到 Spring Boot 開發 WebService 服務,本章研究基於 CXF 調用 WebService。另外本來想寫一篇 xfire 作為 client 端來調用 webservice 的代碼。后來發現 xfire 在2007 你那巔峰時刻,已經不再更新,而后來的 Spring 已經拋棄了部分 Api。導致現在已經不兼容了。
1 新建 Spring Boot Maven 示例工程項目
注意:是用來 IDEA 開發工具
- File > New > Project,如下圖選擇
Spring Initializr然后點擊 【Next】下一步 - 填寫
GroupId(包名)、Artifact(項目名) 即可。點擊 下一步
groupId=com.fishpro
artifactId=webserviceclient - 選擇依賴
Spring Web Starter前面打鈎。 - 項目名設置為
spring-boot-study-webserviceclient.
2 引入依賴 Pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-spring-boot-starter-jaxws -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3 編寫調用代碼
- 實例化 JaxWsDynamicClientFactory
- 建立Client請求
- invoke方法入口,並傳遞參數
http://localhost:8080/ws/user?wsdl 為上一章我們編寫的示例。
@SpringBootApplication
public class WebserviceclientApplication {
public static void main(String[] args) {
SpringApplication.run(WebserviceclientApplication.class, args);
JaxWsDynamicClientFactory dcflient=JaxWsDynamicClientFactory.newInstance();
Client client=dcflient.createClient("http://localhost:8080/ws/user?wsdl");
try{
Object[] objects=client.invoke("getUserById","1");
System.out.println("getUserById 調用結果:"+objects[0].toString());
Object[] objectall=client.invoke("getUsers");
System.out.println("getUsers調用部分結果:"+objectall[0].toString());
}catch (Exception e){
e.printStackTrace();
}
}
}
右鍵 WebserviceclientApplication 點擊 Run WebserviceclientApplication
2019-08-12 18:42:42.341 INFO 63593 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8087 (http) with context path ''
2019-08-12 18:42:42.344 INFO 63593 --- [ main] c.f.w.WebserviceclientApplication : Started WebserviceclientApplication in 2.527 seconds (JVM running for 3.132)
getUserById 調用結果:com.youdomain.webservice.UserDto@3c7d8a4
getUsers調用部分結果:[com.youdomain.webservice.UserDto@4e2824b1, com.youdomain.webservice.UserDto@534d0e20, com.youdomain.webservice.UserDto@7d18338b, com.youdomain.webservice.UserDto@3f4a605f]
