IOException 下载在 Java 中使用用户名和密码保护的文件时



问题:

我想下载一个以给定间隔放置在我们学校服务器上的文件。我想访问的.xml文件位于登录名后面,但至少在浏览器中,您可以通过修改 URL 来访问该文件而无需使用登录名:

https://username:password@subdomain.domain.net/xmlFile.xml

但是如果我想访问该页面,Java会抛出IOException。像这个 W3 示例这样的其他文件可以正常工作。

我当前用于下载文件的代码如下所示:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
URL webServer = new URL(url);
//url is the specified address I want to access.
InputStream stream = webServer.openStream();
Document xmlDatei = docBuilder.parse(stream);
return xmlDatei

问题:

是否有特殊的参数或函数可以用来防止这种情况发生?

尝试使用基本身份验证来访问文件。

String webPage = "http://www.myserver.com/myfile.xml";
String name = "username";
String password = "password";
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
try (InputStream stream = urlConnection.getInputStream()) {
// preparation steps to use docBuilder ....
Document xmlDatei = docBuilder.parse(stream);
}

最新更新