Downloading files from the Internet using Java: how to authenticate?
How to download and save a file from Internet using Java?
Using the code published in the last comment, I get this exception:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://myserver/systemc-2.0.1.tgz at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1305) at java.net.URL.openStream(URL.java:1009) at mypackage.Installer.installSystemc201(Installer.java:29) at mypackage.Installer.main(Installer.java:38)
thank you,
Solution
You implemented the authenticator class and registered it The JavaDocs in the link explains how to
I don't know if this is consistent with the NiO method and gets an accepted answer to the question, but it does apply to the old-fashioned way
In the authenticator class implementation, you may want to use passwordauthentication and override your authenticator implementation's getpasswordauthentication () method to return it This will be the class through the user name and password you need
According to your requirements, here are some sample codes:
public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; private final PasswordAuthentication authentication; public MyAuthenticator(Properties properties) { String userName = properties.getProperty(USERNAME_KEY); String password = properties.getProperty(PASSWORD_KEY); if (userName == null || password == null) { authentication = null; } else { authentication = new PasswordAuthentication(userName,password.tocharArray()); } } protected PasswordAuthentication getpasswordAuthentication() { return authentication; }
And you register it with the main method (or somewhere along the line before you call the URL):
Authenticator.setDefault(new MyAuthenticator(properties));
The usage is simple, but I find that APIs are a collapsed way of thinking about these things Very typical single design