How can I configure the username and password to authenticate a http proxy server using Java?
I just found the following configuration parameters:
http.proxyHost=<proxyAddress> http.proxyPort=<proxyPort> https.proxyHost=<proxyAddress> https.proxyPort=<proxyPort>
But, my proxy server requires authentication. How can I configure my app to use the proxy server?
Java provides proxy handlers for HTTP, HTTPS, FTP, and SOCKS protocols. A proxy can be defined for each handler as a hostname and port number: http. proxyHost – The hostname of the HTTP proxy server.
(EDIT: As pointed out by the OP, the using a java.net.Authenticator
is required too. I'm updating my answer accordingly for the sake of correctness.)
(EDIT#2: As pointed out in another answer, in JDK 8 it's required to remove basic
auth scheme from jdk.http.auth.tunneling.disabledSchemes
property)
For authentication, use java.net.Authenticator
to set proxy's configuration and set the system properties http.proxyUser
and http.proxyPassword
.
final String authUser = "user"; final String authPassword = "password"; Authenticator.setDefault( new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(authUser, authPassword.toCharArray()); } } ); System.setProperty("http.proxyUser", authUser); System.setProperty("http.proxyPassword", authPassword); System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
You're almost there, you just have to append:
-Dhttp.proxyUser=someUserName -Dhttp.proxyPassword=somePassword
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With