Cómo acceder a una URL protegida desde JAVA

Wednesday, February 8, 2012 14:06

Si desde java necesitas conectarte a una URL que está protegida con contraseña de autenticación HTTP, podemos utilizar la clase Authenticator.
Simplemente tendremos que crear una clase que extienda de esta última con los credenciales adecuados para poder conectarnos:

// Install the custom authenticator
Authenticator.setDefault(new MyAuthenticator());
 
// Access the page
try {
    // Create a URL for the desired page
    URL url = new URL("http://hostname:80/index.html");
 
    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
 
public class MyAuthenticator extends Authenticator {
    // This method is called when a password-protected URL is accessed
    protected PasswordAuthentication getPasswordAuthentication() {
        // Get information about the request
        String promptString = getRequestingPrompt();
        String hostname = getRequestingHost();
        InetAddress ipaddr = getRequestingSite();
        int port = getRequestingPort();
 
        // Get the username from the user...
        String username = "myusername";
 
        // Get the password from the user...
        String password = "mypassword";
 
        // Return the information
        return new PasswordAuthentication(username, password.toCharArray());
    }
}
You can leave a response, or trackback from your own site.

One Response to “Cómo acceder a una URL protegida desde JAVA”

  1. Tu Cargador Solar says:

    February 10th, 2012 at 11:08 am

    Muchas gracias! Me ha servido.

Leave a Reply