Search code examples
javainputstreamhttpurlconnection

IOException when downloading file that is secured with username and password in Java


Issue:

I want to download a file that is laying on our school servers at a given interval. The .xml file I want to access lays behind a login, but you can, at least in a browser, access the file without using a login by modifying the URL:

https://username:[email protected]/xmlFile.xml

But Java throws an IOException if I want to access the page. Other files like this W3 example work without any problems.

My current code used for downloading files looks like this:

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

Question:

Are there special arguments or functions that I can use to prevent this from happening?


Solution

  • Try to use Basic Authentication to access your file.

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