Java request through proxy with apache httpclient

Few weeks ago I was solving problem which consisted of calling url in Java program through proxy. It took me a while to figure out correct combination :) so I am sharing sample code that worked for me. I was doing request through Microsoft proxy NTLMv2.

Here is the main code:

 

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.util.EntityUtils;

/**
 * Hello proxy world!
 * 
 */
public class App {
    final static String PROXY_ADDRESS = ""; // proxy (IP) address 

    final static String USERNAME = ""; // username for proxy authentication

    final static String PASSWORD = ""; // password for proxy authentication

    final static String PROXY_DOMAIN = ""; // proxy domain

    public static void main(String[] args) {

	String url = "http://www.the-swamp.info"; // url we want to make request to

	// the rest is combination of documentation for apache http library and Stackoverflow Q&A :)
	HttpHost proxy = new HttpHost(PROXY_ADDRESS, 8080);
	DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
	HttpGet get = new HttpGet(url);

	AuthCache authCache = new BasicAuthCache();
	CredentialsProvider credsProvider = new BasicCredentialsProvider();
	credsProvider.setCredentials(new AuthScope(PROXY_ADDRESS, 8080, AuthScope.ANY_HOST, "ntlm"), new NTCredentials(USERNAME, PASSWORD, "", PROXY_DOMAIN));
	HttpClientContext context = HttpClientContext.create();
	context.setCredentialsProvider(credsProvider);
	context.setAuthCache(authCache);

	CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setRoutePlanner(routePlanner).build();

	try {
	    HttpResponse resp = httpclient.execute(get, context);
	    int httpCode = resp.getStatusLine().getStatusCode();
	    HttpEntity entity = resp.getEntity();
	    String responseString = EntityUtils.toString(entity, "UTF-8");
	    System.out.println(httpCode);
	    System.out.println(responseString);
	} catch (IOException e) {
	    e.printStackTrace();
	}

    }
}

only requirement is Apache Http library:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
  <version>4.3.3</version>
</dependency>
blog comments powered by Disqus