Accediendo a un sitio HTTP/HTTPS desde Java

Posted on Febrero 14, 2008. Filed under: Java | Tags: , , |

En este post veremos como realizar conexiones tanto a sitios HTTP como a sitios HTTPS desde Java. Para ello utilizaremos las clases URLConnection y Authenticator (para el caso especial de HTTPS)


Clase URLConnection

URLConnection es una clase abstracta que implementan todas aquellas clases que quieren mantener un vinculo entre una aplicación y una URL determinada.

Si invocamos al método openConnection de URL, nos devolverá la implementación de URLConnection más apropiada a utilizar.

Por ejemplo si realizamos:


URL url = new URL("http://lefunes.wordpress.com");
URLConnection con = url.openConnection();

dentro de con tendremos un objeto HttpURLConnection, mientras que si la URL hubiese sido HTTPS tendríamos despues del openConnection un objeto HttpsURLConnection.

Accediendo a un sitio HTTP

Abrimos un URLConnection a partir de la URL especificada, como por ejemplo:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
   public static void main(String[] args)
     throws MalformedURLException, IOException {
      URL url = new URL("http://lefunes.wordpress.com");
      URLConnection con = url.openConnection();

      BufferedReader in = new BufferedReader(
         new InputStreamReader(con.getInputStream()));

      String linea;
      while ((linea = in.readLine()) != null) {
         System.out.println(linea);
      }
   }
}

Accediendo a un sitio HTTPS

Al igual que en el caso anterior especifiquemos una URL, pero ahora una cuyo protocolo sea HTTPS, por lo que tendremos:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
   public static void main(String[] args)
    throws MalformedURLException, IOException {
      URL url = new URL("https://algun_servidor…");
      URLConnection con = url.openConnection();

      BufferedReader in = new BufferedReader(
         new InputStreamReader(con.getInputStream()));

      String linea;
      while ((linea = in.readLine()) != null) {
         System.out.println(linea);
      }
   }
}

Si ejecutamos este código tendremos la siguiente excepción:

Exception in thread “main” java.io.IOException: Server returned HTTP response code: 401 for URL: https://algun_servidor…
at sun.net.www.protocol.http.HttpURLConnection.getInputStream (HttpURLConnection.java:1241)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream (HttpsURLConnectionImpl.java:234)
at ejemplo.Main.main(Main.java:57)
Java Result: 1

esta excepción se produce porque nos falta realizar la autenticación para ingresar al sitio.

Para conseguir autenticarnos utilizaremos la clase java.net.Authenticator, sobrescribiendo el método getPasswordAuthentication(). Este método debe devolver un objeto del tipo java.net.PasswordAuthentication seteado tanto con el usuario y clave.

Para realizar esto lo hacemos de la siguiente forma:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;

public class Main {
   public static void main(String[] args)
    throws MalformedURLException, IOException {

      URL url = new URL("https://algun_servidor…");
      URLConnection con = url.openConnection();

      Authenticator au = new Authenticator() {
         @Override
         protected PasswordAuthentication
            getPasswordAuthentication() {
            return new PasswordAuthentication
               ("usuario", "clave".toCharArray());
         }
      };
      Authenticator.setDefault(au);

      BufferedReader in = new BufferedReader(
         new InputStreamReader(con.getInputStream()));

      String linea;
      while ((linea = in.readLine()) != null) {
         System.out.println(linea);
      }
   }
}

y listo, ahí podremos acceder.Hasta la próxima.

Más Info:

Make a Comment

Make A Comment: ( 2 so far )

blockquote and a tags work here.

2 Responses to “Accediendo a un sitio HTTP/HTTPS desde Java”

RSS Feed for Le Funes Comments RSS Feed

Excelente Post.

Saludos

Malvenido

Sebastian Arbona
Marzo 2, 2008

Muchas gracias Seba

Nos estamos viendo.

lefunes
Marzo 2, 2008

Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...