FileUtils copyURLToFile基本身份验证

问题描述 投票:5回答:1

如何传递用户凭据以使用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());
      }
   }

然后进入主目录:

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();
         }
   }

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

java basic-authentication apache-commons fileutils
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.