if (port > 0) prompt += ":" + port;
}
else {
prompt = "";
}
}
mainLabel.setText("Please enter username and password for "
+ prompt + ": ");
passwordDialog.pack( );
passwordDialog.show( );
}
PasswordAuthentication response = null;
class OKResponse implements ActionListener {
public void actionPerformed(ActionEvent e) {
passwordDialog.hide( );
// The password is returned as an array of
// chars for security reasons.
char[] password = passwordField.getPassword( );
String username = usernameField.getText( );
// Erase the password in case this is used again.
passwordField.setText("");
response = new PasswordAuthentication(username, password);
}
}
class CancelResponse implements ActionListener {
public void actionPerformed(ActionEvent e) {
passwordDialog.hide( );
// Erase the password in case this is used again.
passwordField.setText("");
response = null;
}
}
public PasswordAuthentication getPasswordAuthentication( ) {
this.show( );
return this.response;
}
}
例子7-14是经过修改后的SourceViewer 程序,通过DialogAuthenticator 类向用户获取用户名和密码。
Example 7-14. 用来下载受密码保护网页的程序
import java.net.*;
import java.io.*;
import com.macfaq.net.DialogAuthenticator;
public class SecureSourceViewer {
public static void main (String args[]) {
Authenticator.setDefault(new DialogAuthenticator( ));
for (int i = 0; i < args.length; i++) {
try {
//Open the URL for reading
URL u = new URL(args[i]);
InputStream in = u.openStream( );
// buffer the input to increase performance
in = new BufferedInputStream(in);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read( )) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a parseable URL");
}
catch (IOException ex) {
System.err.println(ex);
}
// print a blank line to separate pages
System.out.println( );