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

问题描述 投票:0回答:1

问题:

我想下载一个以给定间隔放置在我们学校服务器上的文件。我要访问的.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

问题:

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

java inputstream httpurlconnection
1个回答
0
投票

尝试使用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);

        }
© www.soinside.com 2019 - 2024. All rights reserved.