En el post anterior aquí (aquí) vimos como se creaba un servicio web que nos devolvía en XML las direcciones que tenemos almacenadas. Ahora vamos a consumir el servicio web mediante un DefaultHttpClient y un HttpGet que nos traerán la información. Una vez realizado este paso tenemos que usar de nuevo el Unmarshall para extraer un objeto DireccionResponse y tendremos así en su interior una lista con las direcciones que tenemos en base de datos. El código que tenemos que emplear es el siguiente:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
DefaultHttpClient httpClient = new DefaultHttpClient();
String url = "http://localhost:8080/noise/direccionesfind/";
HttpGet httpget = new HttpGet(url);
System.out.println("executing request" + httpget.getRequestLine());
try{
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String result= EntityUtils.toString(entity, HTTP.UTF_8);
EntityUtils.consume(entity);
System.out.println("Response content length: " + entity.getContentLength());
System.out.println("Result: " + result);
JAXBContext jaxbContext = JAXBContext.newInstance(DireccionResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader sr = new StringReader(result);
DireccionResponse direcciones = (DireccionResponse) jaxbUnmarshaller.unmarshal(sr);
Iterator it = direcciones.getList().iterator();
while(it.hasNext()){
Direccion direccion = (Direccion) it.next();
System.out.println("Direccion: " + direccion.getCalle());
}
}
catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
No ponemos el código completo ya que lo tengo dentro de otro proyecto. Simplemente tenemos que crearnos una clase o un método donde nos interese consumir un servicio web con el código que hemos indicado anteriormente. Como podemos ver, nos creamos un DefaultHttpClient y el HttpGet. Ejecutamos la conexión mediante el HttpResponse y el execute y así tendremos el contenido del servicio web. Solamente nos falta ahora realizar las labores de Unmarshalling tal y como vimos en el post anterior (aquí). Mostramos entonces en consola la calle de los objetos que nos hemos cargado y vemos así la siguiente información:
No hay comentarios :
Publicar un comentario