miércoles, 12 de marzo de 2014

Utilizando la API de JAVA.NET para leer data en formato JSON desde una URL

Java.net permite realizar conexiones y transacciones a través de la red. Utilizando el paquete java.net podemos comunicar dos o más computadoras que estén en distintas partes del mundo.

En nuestro código de ejemplo vamos a utilizar la clase HttpURLConnection la cual extiende de la clase URLConnection y da soporte especifico al protocolo HTTP.

Ejemplo:

public static String httpGet(String stringUrl) throws HttpGetException{
  URL url;
  try {
   url = new URL(stringUrl);
  } catch (MalformedURLException e2) {
   throw new HttpGetException(e2.getCause());
  }
  HttpURLConnection urlConnection = null;
  String dataJson = "";
  try {
   urlConnection = (HttpURLConnection) url.openConnection();
   urlConnection.setConnectTimeout(5000); // set timeout to 5 seconds
   BufferedReader in = new BufferedReader(new InputStreamReader(
     urlConnection.getInputStream(), StandardCharsets.UTF_8));
   StringBuffer sb = new StringBuffer();
   String inputLine;
   while ((inputLine = in.readLine()) != null) {
    sb.append(inputLine);
   }
   dataJson = sb.toString();
  } catch (java.net.SocketTimeoutException e) {
   throw new HttpGetException(e);
  } catch (IOException e) {
   if (urlConnection instanceof HttpURLConnection) {
    HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
    InputStream in = null;
    try {
     in = httpConn.getErrorStream();
     StringBuffer buf = new StringBuffer();
     byte[] cbuf = new byte[1024 * 64];
     int r = in.read(cbuf);
     while (r > -1) {
      if (r > 0) {
       buf.append(new String(cbuf, 0, r));
      }
      r = in.read(cbuf);
     }
     YoutubeJsonError jsonError = new YoutubeJsonError(
       buf.toString());
     throw new HttpGetException(jsonError.getMessage());

    } catch (IOException e1) {
     e1.printStackTrace();
    } finally {
     if (in != null) {
      try {
       in.close();
      } catch (IOException e1) {
       e1.printStackTrace();
      }
     }
    }

   }
  } finally {
   if (urlConnection != null) {
    urlConnection.disconnect();
   }
  } 
  return dataJson;
 }
}

Probando el método con la siguiente url:
http://ip.jsontest.com/

y con el metodo:
System.out.println(dataJson);


Deberia mostrar el siguiente texto:
{"ip": "8.8.8.8"} donde los numeros ochos representaran la direccion de tu ip en la internet.

No hay comentarios:

Publicar un comentario