前几天领导发给我个 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!!"); } }