2

I need to download a text file using basic authentication (the kind of authentication that prompts the browser to ask you for domain\username and password) using Groovy. I would like to avoid using additional libraries, isn't there anything to do this in in Groovy?

My current code is:

new File("test.txt").withOutputStream { out ->
    def url = new URL(myurl).openConnection()

    def remoteAuth = "Basic " + "myusername:mypassword".bytes.encodeBase64()
    url.setRequestProperty("Authorization", remoteAuth);
    out << url.inputStream
}

But the server replies with a 401 error. What should I do?

user3804769
  • 469
  • 1
  • 8
  • 19

1 Answers1

7

Groovy uses the java.net.Authenticator API. You can provide a default Authenticator using java.net.Authenticator#setDefault. An Example for an BasicAuth usage can be found in another Answer.

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});
Mene
  • 3,739
  • 21
  • 40