I'm using java Proxy class and passing it to HttpURLConnection.openConnection().
Is there a way to provide authentication information (just like http.proxyUser and http.proxyPassword) to the Proxy class?
Thanks
1 Answer
You can use Authenticator for that purpose:
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("login", "password".toCharArray());
}
});
4 Comments
danieln
Will it affect the whole communication or just the relevant connection I'm opening?
Guillaume Polet
@danieln Authenticator is static, so it is global to your application. But it will be invoked only if necessary. If you opened other connections that donnot require authentication, it won't be invoked.
danieln
So it is global to my application but not to the entire application server? (like http.proxyUser). And what if I want different authentications for different connections?
Guillaume Polet
@danieln inside the method
getPasswordAuthentication() you can interrogate the Authenticator to find out for which request authentication is requested (getRequestingURL(), etc...)