FileUtils copyURLToFile BasicAuthenication

Mic*_*izo 5 java basic-authentication apache-commons fileutils

如何使用 apache commons FileUtils 传递用于下载文件的用户凭据?

我正在使用如下身份验证器,但似乎不起作用。它甚至不会抱怨凭据不良,因此看起来我的身份验证器被忽略了。我不断收到 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());
      }
   }
Run Code Online (Sandbox Code Playgroud)

然后在主要:

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();
         }
   }
Run Code Online (Sandbox Code Playgroud)

我可以使用正确的凭据通过邮递员下载。我可以使用 FileUtils 在不使用凭据的情况下下载非安全文件。

Sha*_*ybc 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);
Run Code Online (Sandbox Code Playgroud)