Java 使用身份验证从 url 下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23765282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
download file from url with authentication
提问by surya
i have a secured url , if i open in browser, a pop up comes and i authenitcate with userid/password, then a pdf file is downloaded .
我有一个安全的 url,如果我在浏览器中打开,会弹出一个窗口,我使用用户 ID/密码进行身份验证,然后下载一个 pdf 文件。
I want this functionality in java. It should authenticate using proxy server/port and user details then download
我想在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
It gives me connection timeout error.
它给了我连接超时错误。
Then i thought adding authentication
然后我想添加身份验证
String authentication = "Basic " + new
sun.misc.BASE64Encoder().encode("myuserid:mypassword".getBytes());
connection.setRequestProperty("Proxy-Authorization", authentication);
Still doesnt work,
还是不行,
Please let me know .
请告诉我 。
采纳答案by surya
I solved this issue. I used a customized authenticator before connecting the URL, and it authenticates and downloads the document. FYI - once connected, till next server restart, it doesn't need authentication.
我解决了这个问题。我在连接 URL 之前使用了一个定制的身份验证器,它对文档进行身份验证和下载。仅供参考 - 一旦连接,直到下一次服务器重新启动,它不需要身份验证。
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
Define your own authenticator as given below
定义您自己的身份验证器,如下所示
public class MyAuthenticator extends Authenticator {
final PasswordAuthentication authentication;
public MyAuthenticator(String userName, String password) {
authentication = new PasswordAuthentication(userName, password.toCharArray());
}
}