I would like to fetch a SSL page in Java. The problem is, that I have to authenticate against a http proxy.
So I want a simple way to fetch this page. I tried the Apache Commons httpclient, but it's too much overhead for my problem.
I tried this piece of code, but it does not contain an authentication action:
import java.io.*;
import java.net.*;
public class ProxyTest {
  public static void main(String[] args) throws ClientProtocolException, IOException {
    URL url = new URL("https://ssl.site");
    Socket s = new Socket("proxy.address", 8080);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, s.getLocalSocketAddress());
    URLConnection connection = url.openConnection(proxy);
    InputStream inputStream = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String tmpLine = "";
    while ((tmpLine = br.readLine()) != null) {
      System.out.println(tmpLine);
    }
  }
}
Can anyone provide some information how to implement it on an easy way?
Thanks in advance
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
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