FileUtils copyURLToFile BasicAuthenication

4k views Asked by At

How do I pass in user credentials for downloading files using apache commons FileUtils?

I'm using an authenticator as below but doesn't seem to be working. It does not even complain about bad credentials so it looks like my authenicator is being ignored. I Keep getting a 403.

    import java.net.Authenticator;
    import java.net.PasswordAuthentication;

    public class MyAuthenticator extends Authenticator {
       private static String username = "myUser";
       private static String password = "myPass";

       @Override
       protected PasswordAuthentication getPasswordAuthentication() {
           return new PasswordAuthentication (username, 
               password.toCharArray());
      }
   }

Then in main:

public static void main( String[] args )
    {      
        // Install Authenticator
        Authenticator.setDefault(new MyAuthenticator());

        try {   
        FileUtils.copyURLToFile((new URL("https://example.com/api/core/v3/stuff/611636/data?v=1"), 
                                 new File("d:\\example\\dir1\\subdir1\\myFile.tar"));

        } catch (IOException e) {
            e.printStackTrace();
         }
   }

I'm able to download via postman using correct credentials. I am able to download non secure files without using credentials using FileUtils.

1

There are 1 answers

0
Shaybc On
import org.apache.commons.io.IOUtils;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

String basicAuthenticationEncoded = Base64.getEncoder().encodeToString(user + ":" + password).getBytes("UTF-8"));
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthenticationEncoded);
IOUtils.copy(urlConnection.getInputStream(), fileOutputStream);