如何传递使用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下载不安全的文件,而无需使用凭据。
发布于 2020-01-24 06:53:32
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);https://stackoverflow.com/questions/46259498
复制相似问题