February 2016 Posts

How to Create A HTTP Request with Proxy Using Apache HTTP Client

In this tutorial, im trying to simuate a http GET request using apache http client, the version im using is 4.5.1

<!-- http client -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.1</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.1</version>
</dependency>

Usually, my application connects well without proxy. But on production environment, I need to put a proxy configuration. So this is my method for making a proxy request connection.

public String process(String lat, String lon) {
	try {
		HttpClient httpclient = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet("<INPUT YOUR URL HERE>");
		
		HttpHost proxy = new HttpHost("127.0.0.1", 3128, "http");
		RequestConfig config = RequestConfig.custom()
				.setProxy(proxy)
				.build();
		httpGet.setConfig(config);
		
		HttpResponse response = httpclient.execute(httpGet);
		HttpEntity resEntity = response.getEntity();

		String responseText = EntityUtils.toString(resEntity);		
		return responseText;
	} catch (IOException e) {
		logger.error(e, e);
	} catch (Exception e) {
		logger.error(e, e);
	}
	return null;
}
Google+