views:

625

answers:

5

If I do this...

conn = new URL(urlString).openConnection();
System.out.println("Proxy? " + conn.usingProxy());

it prints

Proxy? false

The problem is, I am behind a proxy. Where does the JVM get its proxy information from on Windows? How do I set this up? All my other apps seem perfectly happy with my proxy.

+5  A: 

This is fairly easy to answer from the internet. Set system properties http.proxyHost and http.proxyPort. You can do this with System.setProperty(), or from the command line with the -D syntax.

Sean Owen
Thanks internet!
izb
+2  A: 

Set following before you openConnection,

System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port_number");

If proxy requires authentication,

System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");
ZZ Coder
I actually think "http.proxyUser" and "http.proxyPassword" are not supported anymore.See http://stackoverflow.com/questions/120797/how-do-i-set-the-proxy-to-be-used-by-the-jvm for more details.
p3t0r
+3  A: 

Proxies are supported through two system properties: http.proxyHost and http.proxyPort. They must be set to the proxy server and port respectively. The following basic example illustrates it:

String url = "http://www.google.com/",
       proxy = "proxy.mydomain.com",
       port = "8080";
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);
Pascal Thivent
@Pascal Do you happen to know what are the major differences of using latest Java approach in comparison to Apache `commons-httpclient`? As Java supports proxying and authentication (as you mentioned here http://stackoverflow.com/questions/1626549/authenticated-http-proxy-with-java), for simple cases (like retrieve one file from public HTTP server) there is no reason to use Apache library. What is your recommendation?
dma_k
@dma_k I agree with you, for simple use cases like the one you described I wouldn't use a third party library.
Pascal Thivent
+3  A: 

Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection() method:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
NickDK
can we provide proxy username and proxy password through it.
Xolve
A: 

I'm using the System.setProperty() method before I create the connection yet conn.usingProxy() always report false (using Java 6)

Does it only use the proxy if required, my test computer does not need to use a proxy but I need to write this software for computers that do ?