This Post will explain you, What is Proxy and  How to connect to a Proxy using a java program. A full example with detailed explanation ensures you to get a complete idea of the proxy concept.

Sometimes we may need to connect to an URL or some resource from your application or java program via a proxy. Before showing you the code first let me explain you what is proxy? It’s purpose and how to use it?

What is a Proxy Server?

Proxy is an intermediate server which connects some set of machines and when one of those machines makes a request, proxy handles that request and sends its IP Address instead of actual machines IP.  This ensures

1. Faster response because the request would have already made my some other machine and so it may remain in cache. Some proxy servers also connects with memcached servers for faster response times.

2.  Administrator can monitor and filter the requests going outside to non intended websites and also he can restricts them.

3. Anonymous and hence more secure obviously.

Proxy Server

 

Full Example of proxy connection in java

ProxyConnections.java


package com.developprojects.javasnippets;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class ProxyConnections {

public static void main(String args[]) {
try {
URL url = new URL(
"http://developprojects.com/wp-content/uploads/2013/12/logo_developProjects.png");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
"proxy.Test.com", 4327));
URLConnection connection = url.openConnection(proxy);
} catch (MalformedURLException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}

}

}

References:

https://www.whatismyip.com/what-is-a-proxy/

 



Swarup Reddy (13 Posts)

Founder of Developprojects.com. He is an Oracle certified expert java developer. He is proficient in end-to-end development right from requirement analysis to system study, designing, coding, testing, de- bugging, documentation and implementation. His areas of interests are Information Security, Programming, compiler designing and automation.