从身份验证下载url文件

时间:2014-05-20 16:28:29

标签: java url download

我有一个安全的网址,如果我在浏览器中打开,弹出窗口,我用userid /密码验证,然后下载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);

仍然无法正常工作,

请告诉我。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。 我在连接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

定义您自己的身份验证器,如下所示

public class MyAuthenticator extends Authenticator {
    final PasswordAuthentication authentication;

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