spring boot如何调用webservice接口
时间: 2023-09-28 19:08:33 浏览: 176
Spring Boot可以使用JAX-WS或者Spring Web Services(Spring-WS)来调用SOAP Web Service接口,也可以使用RestTemplate来调用RESTful Web Service接口。
以下是使用Spring-WS调用SOAP Web Service接口的步骤:
1. 引入Spring-WS和JAXB相关依赖
```xml
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
</dependency>
```
2. 配置WebServiceTemplate
在配置类中添加WebServiceTemplate的Bean,并设置WebServiceTemplate的Marshaller和Unmarshaller,这里使用Jaxb2Marshaller
```java
@Configuration
public class WebServiceConfig {
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.example.webservice.demo.wsdl");
return marshaller;
}
@Bean
public WebServiceTemplate webServiceTemplate() {
WebServiceTemplate template = new WebServiceTemplate();
template.setMarshaller(marshaller());
template.setUnmarshaller(marshaller());
template.setDefaultUri("http://localhost:8080/ws");
return template;
}
}
```
3. 调用WebService
使用WebServiceTemplate的marshalSendAndReceive方法来发送SOAP请求并接收响应,示例代码如下:
```java
@Autowired
private WebServiceTemplate webServiceTemplate;
public void callWebService() {
GetCountryRequest request = new GetCountryRequest();
request.setName("Spain");
GetCountryResponse response = (GetCountryResponse) webServiceTemplate.marshalSendAndReceive(request);
System.out.println(response.getCountry().getCapital());
}
```
以上就是使用Spring-WS调用SOAP Web Service接口的步骤。
阅读全文