【问题标题】:download file from url with authentication通过身份验证从 url 下载文件
【发布时间】:2014-07-09 00:55:46
【问题描述】:

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

还是不行,

请告诉我。

【问题讨论】:

  • 只是一个想法:你能用new URL("http://username:password@some.site.url/download.aspx?client=xyz&docid=1001");吗?
  • 我没听明白,在我上面的 sn-p 中我使用了一个 URL 对象,它没有用
  • 我认为您可以在 URL 字符串中包含 username:password。虽然我从未尝试过这个,所以我不提供这个作为答案,只是让你尝试一下。
  • url 是第三方的,我不想让他们更改他们的代码,目前如果我可以从浏览器下载 pdf(弹出窗口,我提供凭据,然后下载),我相信这是可能的也有java代码
  • 不要问他们任何事情,只需在 URL 字符串中包含用户名:密码。阅读此en.wikipedia.org/wiki/URL#Syntax

标签: java url download


【解决方案1】:

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

【讨论】:

  • 我知道这是一个旧帖子,我正在处理类似的要求。你能详细说明你是如何通过身份验证下载文件的吗?
猜你喜欢
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多