Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an HTTP proxy in java

Tags:

I am writing a code that connects to websites and checks some code, like a crawler. But I need to connect trough a proxy and change the IP address (so it doesn't show the client's IP in the server logs).

How can this be done through java?

like image 894
Tim Avatar asked Jan 05 '11 00:01

Tim


People also ask

Does Java use Http_proxy?

Java provides proxy handlers for HTTP, HTTPS, FTP, and SOCKS protocols. A proxy can be defined for each handler as a hostname and port number: http. proxyHost – The hostname of the HTTP proxy server.


1 Answers

You can use the java system properties to set up a proxy or pass it as command line options.

You can find some details and samples here.

Ex: Before opening the connection

System.setProperty("http.proxyHost", "myProxyServer.com"); System.setProperty("http.proxyPort", "80"); 

Or you can use the default network proxies configured in the sytem

System.setProperty("java.net.useSystemProxies", "true"); 

Since Java 1.5 you can create a instance of proxy and pass it to the openConnection() method.

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080)); URL url = new URL("http://www.yahoo.com"); HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy); uc.connect(); 

Or as lisak suggested, you can use some 3rd party libraries which supports your need better.

like image 58
Arun P Johny Avatar answered Oct 27 '22 06:10

Arun P Johny