Я пытаюсь получить доступ к URL-адресу, для которого требуется аутентификация по имени пользователя и паролю.Доступ к URL, защищенному паролем
Ошибок при строительстве. Не хватает ли чего-нибудь?
это первый класс, он устанавливает аутентификатор, который будет использоваться в сетевой код
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());
}
}
}
второй класс
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());
}
}
вы получаете всплывающее окно, когда вы пытаетесь получить доступ к URL в браузере –