Thursday, May 31, 2012

Downloading URL with login and password

In javadoc there is no clear way on how to download page that requires Basic Authentication, for example like:


  def result = new URL("http://www.requireslogin.com/").getText()


Fortunately, this is still very possible and not too complicated, just add this somewhere before calling URL:


  java.net.Authenticator.setDefault(new java.net.Authenticator() {
    protected java.net.PasswordAuthentication getPasswordAuthentication() {
      return new java.net.PasswordAuthentication("user", "password".toCharArray());
    }
  });


Possibly it would be better to have login and password as parameters, but this still works.

No comments:

Post a Comment