Springboot 集成 webservice Client
前幾天領導發給我個 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 II
Step 1. 編寫 maven 配置文件 pom.xml,根據 WSDL 生成 domain objects 代碼
- 添加依賴
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
- 添加 maven-jaxb2-plugin 插件
<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)
Step 2. 配置 web service client ,繼承 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 ,所以改成了上面寫法
Step 3. 配置 web service 組件
@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;
}
}
Step 4. 測試運行
運行下面用例,全部通過則證明繼承成功
@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!!");
}
}