java - 下载使用 Java 中的用户名和密码保护的文件时出现 IOException
问题描述
问题:
我想以给定的时间间隔下载我们学校服务器上的文件。我要访问的 .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);
}
推荐阅读
- jquery - 添加“包装器” div 标签来包装其他 html div 标签?
- swift - 类型检查失败,Swift 中的可选值
- python - 如何将csv文件与熊猫连接起来
- javascript - JS中`:`的意义是什么
- c# - 将 [columnnr] 中的 sql 数据拉到字符串中以供以后检查
- java - 如何在 Activiti 进程中从网关调用 Java 方法
- dart - Dart 和 Flutter 中具有强类型属性的匿名对象
- ruby-on-rails - 纱线安装不断失败
- python - 如何计算这个递归函数?
- html - 如何下推 h1 标签或如何设置 h1 标签的位置,使其显示在我的导航栏下方