Search code examples
javasslproxyhttp-proxy

Easiest way to fetch SSL page via a proxy in Java


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


Solution

  • 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();
      }