gpt4 book ai didi

java - 使用身份验证从 url 下载文件

转载 作者:行者123 更新时间:2023-11-29 08:48:49 24 4
gpt4 key购买 nike

我有一个安全的 url,如果我在浏览器中打开,会出现一个弹出窗口,我使用用户 ID/密码进行身份验证,然后下载一个 pdf 文件。

我想在 java 中使用此功能。它应该使用代理服务器/端口和用户详细信息进行身份验证,然后下载

URL server = new URL("http://some.site.url/download.aspx?client=xyz&docid=1001");
System.setProperty("https.proxyUser", userName);
System.setProperty("https.proxyPassword", password);

System.setProperty("https.proxyHost",proxy);
System.setProperty("https.proxyPort",port);

URLConnection connection = (URLConnection)server.openConnection();
connection.connect();
InputStream is = connection.getInputStream();

//then i read this input stream and write to a pdf file in temporary folder

它给我连接超时错误。

然后我想添加身份验证

String authentication = "Basic " + new
sun.misc.BASE64Encoder().encode("myuserid:mypassword".getBytes());
connection.setRequestProperty("Proxy-Authorization", authentication);

还是不行,

请告诉我。

最佳答案

我解决了这个问题。我在连接 URL 之前使用了自定义的身份 validator ,它对文档进行身份验证和下载。仅供引用 - 一旦连接,直到下一次服务器重新启动,它不需要身份验证。

URL server = new URL(url); //works for https and not for http, i needed https in  my case.
Authenticator.setDefault((new MyAuthenticator()));

URLConnection connection = (URLConnection)server.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
.... //write code to fetch inputstream

如下所示定义您自己的身份 validator

public class MyAuthenticator extends Authenticator {
final PasswordAuthentication authentication;

public MyAuthenticator(String userName, String password) {
authentication = new PasswordAuthentication(userName, password.toCharArray());
}
}

关于java - 使用身份验证从 url 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23765282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com