Proxy server is one of the network backbone for any corporate network. There are 2 types of proxy setup
1. Forward Proxy: Used for the outbound traffic going from your network to Internet. It is also called Client Side Proxy.
2. Reverse Proxy: Used for inbound calls where traffic is coming from Internet to your network.
Below picture depicts the 2 proxies
In this article, we will discuss on Forward Proxy setup & dicuss how to route the calls through Forward Proxy from Java Http client calling codes.
Step 1: Forward Proxy Setup in Windows
There are many open source Forward Proxy available like Apache Httpd , Squid etc.
I have chosen Squid for Proxy setup as it has a very easy setup.
First download Squid from https://squid.diladele.com/ & install the msi
This will be installed as a Windows service.
Step 2: Post Installation configuration of Squid
Once installed you will find Squid tray
Click "Open Squid Configuration" option
Add the below one at last of the configuration file, this will speed up the traffic calls.
dns_v4_first on
Step 3: Client calls from Java routing through Proxy
Suppose you want to call https://www.google.com/ from Java Client.
In this example, we will use Spring RestTemplate.
Create a new Maven project.
3.1. Add the below dependencies
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.30.RELEASE</version>
</dependency>
3.2. Sample Code for Proxy call:
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class ProxyHttpClient {
private static String PROXY_SERVER_HOST = "localhost";
private static int PROXY_SERVER_PORT = 3128;
public static void main(String[] args) {
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(proxy);
RestTemplate restTemplate = new RestTemplate(requestFactory);
ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://www.google.com/", String.class);
String bodyStr = responseEntity.getBody();
System.out.println("bodyStr:" + bodyStr);
}
}
Links:
Squid Setup
Proxy Concept