Migrating from HttpClient 3.1 to HttpClient 4.0

We were using Apache HttpClient 3.1 for some time now and have decide to bite the bullet and migrate over to HttpClient 4.0.3. It’s usually painless to¬†update Apache libraries, but HttpClient 4 was a complete rewrite and is not backward compatible. It’s also now a top level Apache project and no longer part of Apache Commons. Here are the things we had to change to migrate over to the latest HttpClient. This is a mini HttpClient 4 tutorial for those moving to the latest version. The time it takes you to migrate depends on how many references you have to change. It took us less than 30 minutes to do it on our project.

1. Replace commons-httpclient-3.1.jar with the latest httpclient-4.0.3.jar and httpmime-4.0.3.jar. You will also need httpcore-4.0.1.jar.

2. Change your import statements from org.apache.commons.httpclient.* to import org.apache.http.*. For example, change:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.ConnectTimeoutException;


import org.apache.http.client.HttpClient;
import org.apache.http.HttpStatus;
import org.apache.http.HttpException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;

Notice the addition of HttpResponse and DefaultHttpClient, which will be used next.

3. Change your code from the old HttpClient interface to the new.

HttpClient 3.1:

HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
	InputStream is = method.getResponseBodyAsStream();
	// do something with the input stream

HttpClient 4.0:

HttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse httpResponse = client.execute(method);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
	InputStream is = httpResponse.getEntity().getContent();
	// do something with the input stream

We certainly did not use the full functionality of HttpClient, and most of our changes were similar to those listed above. For a complete examples on how to use HttpClient 4, visit the HttpClient 4.0.3 Tutorial. Do you have any other tips for HttpClient 3 to 4 migration?