我試圖訪問需要通過用戶名和密碼進行身份驗證的網址。訪問受密碼保護的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());
}
}
你得到當你試圖訪問瀏覽器 –