Sto tentando di accedere a un URL che richiede l'autenticazione tramite nome utente e password.accesso a un URL protetto da password
Non ci sono errori durante la costruzione .. Mi manca qualcosa?
questa è la prima classe, imposta l'autenticatore che verrà utilizzato dal codice di rete
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());
}
}
}
la seconda classe
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());
}
}
state ottenendo un popup quando si tenta di accedere all'URL browser –