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

下载用Java中的用户名和密码保护的文件时发生IOException,java,inputstream,httpurlconnection,Java,Inputstream,Httpurlconnection,问题: 我想下载一个文件,它以给定的间隔放置在我们学校的服务器上。我要访问的.xml文件位于登录之后,但您至少可以在浏览器中通过修改URL访问该文件,而无需使用登录: https://username:password@subdomain.domain.net/xmlFile.xml 但是如果我想访问页面,Java会抛出一个IOException。其他文件喜欢没有任何问题的工作 我当前用于下载文件的代码如下所示: DocumentBuilderFactory dbf = DocumentBui

问题:

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

https://username:password@subdomain.domain.net/xmlFile.xml
但是如果我想访问页面,Java会抛出一个IOException。其他文件喜欢没有任何问题的工作

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

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

        }

-适应这种情况还会给你带来问题吗?可能比您真正需要的进口产品多一些。只是在网上而不是通过IDE实现了。这里没有。不要乱贴标签。你会得到什么
IOException
呢?谢谢!这解决了我的问题。如果其他人有完全相同的问题,您需要将Base64.encodeBase64替换为Base64.getEncoder().encode(在使用Java 8时):)