Java: process http.proxyUser and http.proxyPassword

Some tutorials suggest to use the system properties http.proxyUser and http.proxyPassword to get proxy authentication, but that won't work since - in contrast to http.proxyHost and http.proxyPort - these properties will not be processed by Java's HttpURLConnection.

Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.

The following snippet contains some code that uses an Authenticator to process http.proxyUser, but ensures that these information will be sent to the host that is defined by http.proxyHost:

  1. // Java ignores http.proxyUser. Here come's the workaround.
  2. Authenticator.setDefault(new Authenticator() {
  3. @Override
  4. protected PasswordAuthentication getPasswordAuthentication() {
  5. if (getRequestorType() == RequestorType.PROXY) {
  6. String prot = getRequestingProtocol().toLowerCase();
  7. String host = System.getProperty(prot + ".proxyHost", "");
  8. String port = System.getProperty(prot + ".proxyPort", "");
  9. String user = System.getProperty(prot + ".proxyUser", "");
  10. String password = System.getProperty(prot + ".proxyPassword", "");
  11.  
  12. if (getRequestingHost().toLowerCase().equals(host.toLowerCase())) {
  13. if (Integer.parseInt(port) == getRequestingPort()) {
  14. // Seems to be OK.
  15. return new PasswordAuthentication(user, password.toCharArray());
  16. }
  17. }
  18. }
  19. return null;
  20. }
  21. });

Add new comment