Easiest way to fetch SSL page via a proxy in Java
You need to set a java.net.Authenticator before you open your connection:
...
public static void main(String[] args) throws Exception {
// Set the username and password in a manner which doesn't leave it visible.
final String username = Console.readLine("[%s]", "Proxy Username");
final char[] password = Console.readPassword("[%s"], "Proxy Password:");
// Use a anonymous class for our authenticator for brevity
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
URL url = new URL("https://ssl.site");
...
}
To remove your authenticator after you're finished, call the following code:
Authenticator.setDefault(null);
The authenticator in Java SE 6 supports HTTP Basic
, HTTP Digest
and NTLM
. For more information, see the Http Authentication documentation at sun.com
org.apache.commons.httpclient.HttpClient is your friend,
Sample code from http://hc.apache.org/httpclient-3.x/sslguide.html
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
GetMethod httpget = new GetMethod("https://www.verisign.com/");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}