4/30/2009

Java: How To Use HTTP Connect Via Proxy

Filed under: — Aviran Mordo @ 5:06 am

Java provides a class called java.net.HttpURLConnection which lets you make a single connection to a url, however when you need to make the connection using proxy you are in trouble.

There are couple of methods to connect via proxy. The first one is simply to define system properties which will then let you make an HttpURLConnection using the proxy properties. Here is one way to define the properties

System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("https.proxyPort", "80");

That’s all wonderful with system properties, but what if you need to use a specific proxy for one kind of requests, and another proxy for all others? For instance local HTTP proxy that connects to a corporate proxy and other proxy to connect to the internet, and you need that the requests are issued simultaneously by different threads? Changing system.properties obviously won’t help.

Take a look at abstract class java.net.HttpURLConnection. It requires concrete implementation, and Sun provides one: sun.net.www.protocol.http.HttpURLConnection. It even has a public constructor public HttpURLConnection(URL url, String s, int i), that accepts parameters of target URL, proxy host name and proxy port! All you need to do is instantiate it directly, and not obtain from java.net.URL.openConnection(), and there you go, http connection via proxy.

sun.net.www.protocol.http.HttpURLConnection conn = new HttpURLConnection(requestedURL, "127.0.0.1",80);

 

Leave a Reply

You must have Javascript enabled in order to submit comments.

All fields are optional (except comment).
Some comments may be held for moderation (depends on spam filter) and not show up immediately.
Links will automatically get rel="nofollow" attribute to deter spammers.

Powered by WordPress