Java Reference
In-Depth Information
final static String PASSWORD = "user1";
static class BasicAuthenticator extends Authenticator
{
@Override
public PasswordAuthentication getPasswordAuthentica-
tion()
{
System.out.println("Password requested from "+
getRequestingHost()+" for au-
thentication "+
"scheme
"+getRequestingS-
cheme());
return
new
PasswordAuthentication(USERNAME,
PASSWORD.toCharArray());
}
}
public static void main(String[] args) throws IOExcep-
tion
{
Authenticator.setDefault(new BasicAuthenticator());
String s = "http://test.webdav.org/auth-basic/";
URL url = new URL(s);
URLConnection urlc = url.openConnection();
Map<String,List<String>>
hf
=
urlc.getHeaderFields();
for (String key: hf.keySet())
System.out.println(key+":
"+urlc.getHeaderField(key));
System.out.println(((HttpURLConnection)
urlc).getResponseCode());
}
}
Because Authenticator is abstract, it must be subclassed. Its protected
PasswordAuthentication getPasswordAuthentication() method
must be overridden to return the username and password in a
java.net.PasswordAuthentication object. Finally, the void setDe-
Search WWH ::




Custom Search