java.net.Authenticator
The class Authenticator
represents an object that knows how to obtain authentication for a network
connection. Usually, it will do this by prompting the user for information.
Applications use this class by overriding getPasswordAuthentication()
in a sub-class. This method will
typically use the various getXXX()
accessor methods to get information about the entity requesting
authentication. It must then acquire a username and password either by interacting with the user or through some other
non-interactive means. The credentials are then returned as a PasswordAuthentication
return value.
An instance of this concrete sub-class is then registered with the system by calling setDefault(Authenticator)
.
When authentication is required, the system will invoke one of the requestPasswordAuthentication()
methods
which in turn will call the getPasswordAuthentication()
method of the registered object.
HttpURLConnection
supports proxy authentication through the Authenticator
class. To enable
authentication, your application subclasses Authenticator
and defines the
getPasswordAuthentication()
method. A minimalist implementation is as follows:
public class SimpleAuthenticator extends Authenticator { private String username, password; public SimpleAuthenticator(String username,String password) { this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username,password.toCharArray()); } }
Next, it must register the authenticator through Authenticator.setDefault()
. If we adapt the previous
code sample to use Authenticator
, it looks like this:
String url = "http://java.boot.by/"; String proxy = "proxy.mydomain.com"; String port = "8080"; String username = "mikalai"; String password = "pwd"; Authenticator.setDefault(new SimpleAuthenticator(username,password)); URL server = new URL(url); Properties systemProperties = System.getProperties(); systemProperties.setProperty("http.proxyHost",proxy); systemProperties.setProperty("http.proxyPort",port); HttpURLConnection connection = (HttpURLConnection)server.openConnection(); connection.connect(); InputStream in = connection.getInputStream(); readResponse(in);
![]() |
![]() ![]() |