Authenticated HTTP proxy with Java

Viewed 215698

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?

8 Answers

Since no one has mentioned this and I have seen a few examples where Authenticator.setDefault, this can cause unintentionally leaking of your username and password. Here is another way of doing this, I think this is much cleaner.

import java.net.*;
import java.util.Base64;

class JavaFileUtil {
  private String hostname = "hostname";
  private int port = 8000;
  private String username = "username";
  private String password = "password";

  private Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port));
  private String authHeader = new String(Base64.getEncoder().encode(new String(username + ":" + password).getBytes()));

  public void download(URL url) {
    HttpURLConnection newConnection = null;
    try {
      newConnection = (HttpURLConnection) url.openConnection(proxy);
      newConnection.setRequestProperty("Proxy-Authorization", "Basic " + authHeader);

      //The rest of your code here

    } catch (Exception e) {
      //log some error or handle it
    } finally {
      //Make sure you close the connection
      if (newConnection != null) newConnection.disconnect();
    }
  }

}
Related