问题:
我想下载一个以给定间隔放置在我们学校服务器上的文件。我要访问的.xml文件位于登录名的后面,但是您至少可以在浏览器中通过修改URL来访问该文件而无需使用登录名:
https://username:[email protected]/xmlFile.xml
但是如果我想访问该页面,Java会抛出IOException。其他文件,例如this W3 example,可以正常工作。
我当前用于下载文件的代码如下:
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
问题:
是否有可以用来防止这种情况发生的特殊参数或函数?
尝试使用Basic Authentication访问您的文件。
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);
}