I'm trying to access a url that needs authentication by a username and password.
There is no errors when building.. Am I missing anything?
this is the first class, it sets the authenticator that will be used by the networking code
public class AccessPasswordProtectedURLWithAuthenticator {
public static void main(String[] args) {
try {
// when a proxy or an HTTP server asks for authentication.
Authenticator.setDefault(new Authenticator(){});
URL url = new URL("http://website.html");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
}
the second class
public class CustomAuthenticator extends Authenticator{
/// Called when password authorization is needed
protected PasswordAuthentication getPasswordAuthentication() {
/// Get information about the request
String prompt = getRequestingPrompt();
String hostname = getRequestingHost();
InetAddress ipaddr = getRequestingSite();
int port = getRequestingPort();
String username = "Administrator";
String password = "Administrator";
/// Return the information (a data holder that is used by Authenticator)
return new PasswordAuthentication(username, password.toCharArray());
}
}
You can use your account management control panel to protect Web pages with a password. If you do this, anyone trying to view those pages will be asked to enter a user name and password using HTTP authentication. A password actually protects all the Web pages in a certain directory (folder).
Click on the 3 vertical dots to the right of the URL and select Details. Click the eye icon to the right of the password to show it. When prompted enter your computer's Windows account credentials. View the password in the field.
Targeted Threat Protection with URL Protect rewrites all links in inbound emails and scans the destination website in real-time when clicked to help ensure malicious websites are blocked, regardless of the client or device in use.
Your first code segment doesn't reference the second class. It should have this code:
Authenticator.setDefault(new CustomAuthenticator());
Have you tried prepending the username and password to the hostname in the URL itself? This may allow you to avoid using the Authenticator altogether:
URL url = new URL("http://username:[email protected]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With