前幾天領導發給我個 webservice 的接口,須要集成下,由於之前並無弄過 webService,因此當時百度出來一個方案以下
Springboot 調用 soap webservice(Client),
當時按照教程很順利的集成裏進去,可是集成後,發現一個問題,就是 jdk 自帶工具 wsimport
生產的代碼將的 url 是寫死在
代碼中,這種很差管理應該提取到配置文件中,可是因爲是寫在靜態代碼塊中,又給咱們帶來了一些麻煩,依靠
spring boot 項目中,webservice 生成客戶端,wsdl 可配置
教程,咱們將 url 提取到了配置文件中。
這幾天我就在想又沒有其餘的寫法果真在 spring 中有 WebServiceTemplate
,
今天就用這個來寫下,而且記錄在這裏,參考文章和代碼來源 Consume Spring SOAP web services using client application – Part IIhtml
pom.xml
,根據 WSDL 生成 domain objects 代碼<dependency> <groupId>org.springframework.ws</groupId> <artifactId>spring-ws-core</artifactId> </dependency>
<plugin> <groupId>org.jvnet.jaxb2.maven2</groupId> <artifactId>maven-jaxb2-plugin</artifactId> <version>0.13.1</version> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <schemaLanguage>WSDL</schemaLanguage> <generatePackage>com.pay.wsdl</generatePackage> <schemas> <schema> <url>http://localhost:8080/ws/pay.wsdl</url> </schema> </schemas> </configuration> </plugin>
我這邊用的是idea,執行 maven → plugins → jaxb2 → generate 就在targetgenerated-sourcesxjc 下生成了
()(./maven-generate.png)java
WebServiceGatewaySupport
類public class PayClient extends WebServiceGatewaySupport { private static final Logger log = LoggerFactory.getLogger(PayClient.class); public RechargeResponse recharge() { Recharge rechargeRequest = new Recharge(); rechargeRequest.setCustomId("141334300009"); return (RechargeResponse) getWebServiceTemplate().marshalSendAndReceive(rechargeRequest,new SoapActionCallback("http://HHHH.net/Recharge")); } }
這裏有個小坑坑 💔
一開始是掉用 WebServiceTemplate 的寫法是getWebServiceTemplate().marshalSendAndReceive(request);
, 可是,調用的時候
報錯【服務器未能識別 HTTP 頭 SOAPAction 的值】,查了下須要添加SOAPAction ,因此改爲了上面寫法web
@Configuration public class SoapClientConfig { @Bean public Jaxb2Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); // this package must match the package in the specified in // pom.xml marshaller.setContextPath("com.pay.wsdl"); return marshaller; } @Bean public PayClient movieClient(Jaxb2Marshaller marshaller) { PayClient client = new PayClient(); client.setDefaultUri("http://localhost:8080/ws/pay.wsdl"); client.setMarshaller(marshaller); client.setUnmarshaller(marshaller); return client; } }
運行下面用例,所有經過則證實繼承成功spring
@SpringBootTest @Slf4j class WebServiceDemoApplicationTests { @Autowired PayClient payClient; @Test void contextLoads() { Assert.notNull(payClient, "payClient is null error"); } @Test void payClientRechange() { RechargeResponse rechargeResponse = payClient.recharge(); Assert.notNull(rechargeResponse, "payClient have not response!!"); } }