How do I setting a proxy for HttpClient?

In this example you will see how to configure proxy when using the Apache Commons HttpClient library.

package org.kodejava.example.commons.httpclient;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;


public class HttpGetProxy {
    private static final String PROXY_HOST = "";
    private static final int PROXY_PORT = 8080;

    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("");

        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(PROXY_HOST, PROXY_PORT);

        String username = "guest";
        String password = "s3cr3t";
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

        client.getState().setProxyCredentials(authScope, credentials);

        try {

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                String response = method.getResponseBodyAsString();
                System.out.println("Response = " + response);
        } catch (IOException e) {
        } finally {

Maven Dependencies

<!-- -->

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳


  1. Hi Wayan Saryada,

    Which version of the jar should use for this program. I am getting NoClassDefFoundError error. Please suggest me.

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException
        at org.apache.commons.httpclient.HttpMethodBase.(
        at org.apache.commons.httpclient.methods.GetMethod.(
        at HttpClientTest.main(
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.DecoderException
        at Method)
        at java.lang.ClassLoader.loadClass(
        at sun.misc.Launcher$AppClassLoader.loadClass(
        at java.lang.ClassLoader.loadClass(
        ... 3 more
  2. Hi Naveen,

    The example requires the commons-httpclient-3.x.jar. When using maven all other dependencies will be downloaded. In this case the DecoderException class is part of the Apache Commons commons-codec-1.2.jar.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.