Using Apache Commons HttpClient to download HTTP data

The Apache HttpClient library makes accessing and downloading HTTP data easy

Published: Saturday, 7 May 2011
Last modified: Monday, 26 November 2012


This used to be standalone but is now under the Apache HttpComponents project. The tutorial should give you enough information on how to use it.

At time of writing we are using version 4.1

Usage snippet

package com.magicmonster.sample;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class HttpClientSnippet {
    public static void main(String[] args) throws Exception {
        String url = "";
        URI uri = new URI(url);
        HttpGet httpget = new HttpGet(uri);

        HttpClient httpclient = new DefaultHttpClient();

        HttpResponse response = httpclient.execute(httpget);
        // check response headers.
        String reasonPhrase = response.getStatusLine().getReasonPhrase();
        int statusCode = response.getStatusLine().getStatusCode();

        System.out.println(String.format("statusCode: %d", statusCode));
        System.out.println(String.format("reasonPhrase: %s", reasonPhrase));

        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 1024);

        // apache IO util
        try {
            System.out.println("start download");
            IOUtils.copy(content, baos);
        } finally {
            // close http network connection
        System.out.println("end download");
        byte[] bytes = baos.toByteArray();
        System.out.println(String.format("got %d bytes", bytes.length));
        System.out.println("HTML as string:" + new String(bytes));

Maven dependencies

To include the httpclient library into your project, use the following maven dependency:


This is the latest version as at 10 Mar 2013.

gzip compression

To turn this on in the client, use a ContentEncodingHttpClient instead of the DefaultHttpClient. e.g. in the snippet above replace the DefaultHttpClient httpclient variable with the following

HttpClient httpclient = new ContentEncodingHttpClient();

Building URLs

The build a URL with request parameters, use the fluent URIBuilder. Note the path needs a leading slash.

import org.apache.http.client.utils.URIBuilder;

URI uri = new URIBuilder()
            .setParameter("foo", "bar")
            .setParameter("query", "this is a test")

The above will output: