views:

220

answers:

4

I need to establish and send/read over/from an https connection (to a website of course) but through an http proxy or SOCKS proxy. A few other requirements

  • supports blocking (I can't use non-blocking/nio)
  • isn't set as an environment or some other global scope property (there are multiple threads accessing)

I was looking into HttpCore components but I did not see any support for blocking https.

A: 
System.setProperty("http.proxyHost", "proxy.com");
System.setPropery("http.proxyPort", "8080");

URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

Sorry, but this won't work because it sets a property and I have multiple threads using different proxies
Zombies
+3  A: 

Look at the java.net.Proxy class. That does what you need. You create one, and then pass it to the URLConnection to create the connection.

Yishai
Hm, is there a way I can tell if it connected via socks4 or socks5? I can only specify "socks" as a type and it seems to try to guess between socsk4,socks4a and socks5?
Zombies
@Zombies, it seems that it attempts to figure it out itself, yes.
Yishai
+1  A: 

Did you look at Apache HTTP Client? Haven't used it in ages but I did use it to pick a proxy server dynamically. Example from site here:

 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();
  }
sal
Hm, but how can this be set to socks4/5/http? It seems only http proxy is accepted?
Zombies
Socks is going to make that much harder. You're likly going to have to hack something up to use the SocketFactory class to pass that socket to the HTTPClient. This is really an ugly problem for a Friday afternoon.
sal
@ZZ Coder mentioned the newer HttpClient4 and that might fix the socks issue.
sal
+2  A: 

To support per-thread proxy, your best bet is Apache HttpClient 4 (Http Components Client). Get the source code,

http://hc.apache.org/downloads.cgi

It comes with examples for both HTTP proxy and SOCKS proxy,

   ClientExecuteProxy.java
   ClientExecuteSOCKS.java
ZZ Coder
Are you sure those examples are packaged in there? a google result shows almost nothing for that file. And a folder search found nothing.
Zombies
This looks like it might help http://mail-archives.apache.org/mod_mbox/hc-commits/201004.mbox/%[email protected]%3E
sal
Try get the source from the SVN. Or you can get it online from here: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/
ZZ Coder