Antes leia:
TDSI – Web Services com GlassFish, JTA / JPA e JSON – parte 6
Agora vamos consumir o Web Service em um programa desktop (pode ser adpatado para funcionar no Android) .
Crie num novo projeto, chamado consometdsiWS tipo Aplicação Java. Dentro dele faça um cópia do pacote Model juntamente com as classes Marca.java e Modelo.java.
Vamos retirar todas as anotações (annotations) JPA (retire os imports também) e deixar somente as Jackson como abaixo:
package model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.util.Date; import java.util.List; @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") public class Marca { @JsonProperty("id") private Long CodMarca; private String NomeMarca; private Date dtfundacao; // getters e setters }
package model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id",scope = Marca.class) public class Modelo { @JsonProperty("id") private Long CodModelo; private String DescricaoModelo; private Marca marca; geters e seters }
E no programa principal vamos colocar os seguintes códigos:
package consometdsiws; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import model.Marca; public class ConsometdsiWS { private static final String targetURL = "http://localhost:8080/tdsiWS/webresources/tdsi/listarmarca"; public static void main(String[] args) throws MalformedURLException, IOException { URL restServiceURL = new URL(targetURL); HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("Accept", "application/json"); if (httpConnection.getResponseCode() != 200) { throw new RuntimeException("HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode()); } BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()))); String output; String json = new String(); while ((output = responseBuffer.readLine()) != null) { json = json + output; } ObjectMapper mapper = new ObjectMapper(); Marca marca; marca = mapper.readValue(json, Marca.class); httpConnection.disconnect(); } }
E o Web Service foi consumido.
Links dos códigos completos