Working behind a proxy and writing network related code has always been boring for me. Just because everytime I had to connect to Internet and get some data, I had to use Proxy settings. Whatever I used had a proxy configuration. HTTP Proxy are configured mostly in corporate environments to manage internet usage. Hence if you are writing a code in Java to connect to internet and get something as we were doing in our Web crawler in Java article, we have to use HTTP proxy settings to get connected to internet. When do you need to consider proxy settings for connecting to internet?
- Your Java client runs on a machine on the Local network – Private LAN. The client could be a standalone application, or a servlet hosted on a web container like Tomcat
- Your code access an external resource using HTTP. For example, invoking an external Web Service.
- Your HTTP call needs to tunnel through the HTTP proxy (using SOCKS authentication). Even if authentication is not required, you would still need to configure the URL and the Port of your HTTP proxy.
Settings for HTTP ProxyUse one of the methods below for your JVM proxy settings. Try an alternate method if any particular method does not work. In most cases, you should not require any change the pre-compiled Java code for proxy settings. JVM’s environment settings should be enough to fix this problem.
Command Line JVM SettingsThe proxy settings are given to the JVM via command line arguments:
Code language: Java (java)
$> java -Dhttp.proxyHost=proxyhostURL -Dhttp.proxyPort=proxyPortNumber -Dhttp.proxyUser=someUserName -Dhttp.proxyPassword=somePassword HelloWorldClass
Setting System Properties in CodeAdd the following lines in your Java code so that JVM uses the proxy to make HTTP calls. This would, of course, require you to recompile your Java source. (The other methods do not require any recompilation):
Hope this works. :)Code language: Java (java)
System.getProperties().put("http.proxyHost", "someProxyURL"); System.getProperties().put("http.proxyPort", "someProxyPort"); System.getProperties().put("http.proxyUser", "someUserName"); System.getProperties().put("http.proxyPassword", "somePassword");