Una vez que sabemos cómo publicar un servicio web, ahora construiremos un cliente que consuma dicho servicio en un proyecto Spring-WS usando WebServiceTemplate
, y le pondremos un timeout de 5 segundos por si el webservice está caído -partiendo del proyecto en eclipse que hacen aquí-.
application-context-ws.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="httpSender"
class="org.springframework.ws.transport.http.CommonsHttpMessageSender">
<property name="connectionTimeout" value="5000" />
<property name="readTimeout" value="5000" />
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="defaultUri"
value="http://localhost:8080/holamundoWS/services/HolaMundoImpl" />
<property name="messageSender" ref="httpSender" />
</bean>
</beans>
—
HolaMundoClienteSpring.java:
package es.lycka.holamundoWS.clientes.spring;
import java.io.StringReader;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ws.client.core.WebServiceTemplate;
public class HolaMundoClienteSpring {
private static final String MESSAGE =
"<getSaludoLycka><nombre>kk</nombre></getSaludoLycka>";
public static void main(String[] args) {
ApplicationContext contexto = new ClassPathXmlApplicationContext(
"/es/lycka/holamundoWS/clientes/spring/application-context-ws.xml");
WebServiceTemplate template = (WebServiceTemplate)contexto.getBean("webServiceTemplate");
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
template.sendSourceAndReceiveToResult(source, result);
System.out.println("resultado = " + result);
}
}
—
Implementado con Eclipse Helios y Apache Tomcat 7.