【发布时间】:2018-02-25 19:44:08
【问题描述】:
如何传递用户凭据以使用 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());
}
}
然后在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();
}
}
我可以使用正确的凭据通过邮递员进行下载。 我可以使用 FileUtils 下载非安全文件,而无需使用凭据。
【问题讨论】:
-
源是否接受基本身份验证?您是否尝试像这样在 url 中传递凭据:
http://username:password@example.com编辑:您是否检查了对目标的请求的外观?尝试调试您的 url 请求,您将看到您的身份验证器是否传递了某些东西。另外:查看copyURLToFile()-Methods 的文档。你也可以传递 timeout-parameters,这将是一个更好的解决方案,因为如果没有设置 timeout,这个方法将永远运行。 -
我最终放弃了 FileUtils 方法并改用了 okhttp3 jar。
-
我用过这个方法。它有效。
标签: java basic-authentication apache-commons fileutils