Java Reference
In-Depth Information
class can access sites that use HTTP authentication, although you'll of course need to
tell it which username and password to use.
Supporting sites that use nonstandard, cookie-based authentication is more challeng‐
ing, not least because this varies a lot from one site to another. Implementing cookie
authentication is hard short of implementing a complete web browser with full HTML
forms and cookie support; we'll discuss Java's cookie support in Chapter 7 . Accessing
sites protected by standard HTTP authentication is much easier.
The Authenticator Class
The java.net package includes an Authenticator class you can use to provide a user‐
name and password for sites that protect themselves using HTTP authentication:
public abstract class Authenticator extends Object
Since Authenticator is an abstract class, you must subclass it. Different subclasses may
retrieve the information in different ways. For example, a character mode program
might just ask the user to type the username and password on System.in . A GUI pro‐
gram would likely put up a dialog box like the one shown in Figure 5-2 . An automated
robot might read the username out of an encrypted file.
Figure 5-2. An authentication dialog
To make the URL class use the subclass, install it as the default authenticator by passing
it to the static Authenticator.setDefault() method:
public static void setDefault ( Authenticator a )
For example, if you've written an Authenticator subclass named DialogAuthentica
tor , you'd install it like this:
Authenticator . setDefault ( new DialogAuthenticator ());
You only need to do this once. From this point forward, when the URL class needs a
username and password, it will ask the DialogAuthenticator using the static Authen
ticator.requestPasswordAuthentication() method:
public static PasswordAuthentication requestPasswordAuthentication (
InetAddress address , int port , String protocol , String prompt , String scheme )
throws SecurityException
 
Search WWH ::




Custom Search