首页 > 解决方案 > 下载使用 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

问题:

我可以使用特殊的参数或函数来防止这种情况发生吗?

标签: javainputstreamhttpurlconnection

解决方案


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

        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);

        }

推荐阅读