5

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.

Micho Rizo
  • 1,000
  • 3
  • 12
  • 27
  • Does the source accept base auth? Did you try to pass the credentials in the url like this: `http://username:password@example.com` Edit: Did you check how the request to your target looks like? Try to debug your url request and you will see if your authenticator is passing something or not. Also: Check the documentation of the `copyURLToFile()`-Methods. You can also pass timeout-parameters, which would be a better solution because if no timeout is set, this method will run forever. – Lama Sep 17 '17 at 10:58
  • I ended up abandoning the FileUtils approach and used okhttp3 jar instead. – Micho Rizo Sep 18 '17 at 14:00
  • 1
    I'v used this method. It works. – M-Razavi Mar 27 '18 at 07:44

1 Answers1

0
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);
Shaybc
  • 2,628
  • 29
  • 43