Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fpmislata.clientejson; import com.fpmislata.domain.Producto; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; /** * * @author alumno */ public class ClienteProductoTest { public static void main(String[] args) throws IOException { System.out.println("Lista de categorias del sistema"); System.out.println("---------------------------"); List<Producto> lista = getListProducto( "http://localhost:8080/ProyectoFinal20162017-web/webservice/ProductosService/Productos"); for (Producto producto : lista) { System.out.println(producto.toString()); } System.out.println("----------------------------\n"); } private static List<Producto> getListProducto(String url) throws IOException { // Crea el cliente para realizar la conexion DefaultHttpClient httpClient = new DefaultHttpClient(); // Crea el mtodo con el que va a realizar la operacion HttpGet httpGet = new HttpGet(url); // Aade las cabeceras al metodo httpGet.addHeader("accept", "application/json; charset=UTF-8"); httpGet.addHeader("Content-type", "application/json; charset=UTF-8"); // Invocamos el servicio rest y obtenemos la respuesta HttpResponse response = httpClient.execute(httpGet); // Obtenemos un objeto String como respuesta del response String lista = readObject(response); // Creamos el objeto Gson que parsear los objetos a JSON, excluyendo los que no tienen la anotacion @Expose Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); // Creamos el tipo generico que nos va a permitir devolver la lista a partir del JSON que esta en el String Type type = new TypeToken<List<Producto>>() { }.getType(); // Parseamos el String lista a un objeto con el gson, devolviendo as un objeto List<Categoria> return gson.fromJson(lista, type); } private static String readObject(HttpResponse httpResponse) throws IOException { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuffer buffer = new StringBuffer(); char[] dataLength = new char[1024]; int read; while ((read = bufferedReader.read(dataLength)) != -1) { buffer.append(dataLength, 0, read); } System.out.println(buffer.toString()); return buffer.toString(); } catch (Exception e) { throw e; } finally { if (bufferedReader != null) { bufferedReader.close(); } } } }