FileUtils copyURLToFile BasicAuthenication
Asked Answered
V

1

6

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.

V answered 17/9, 2017 at 0:0 Comment(3)
Does the source accept base auth? Did you try to pass the credentials in the url like this: http://username:[email protected] 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.Sacellum
I ended up abandoning the FileUtils approach and used okhttp3 jar instead.V
I'v used this method. It works.Bartels
C
1
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);
Circuitous answered 23/1, 2020 at 22:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.