Migrating from HttpClient 3.1 to HttpClient 4.0

来源:互联网 发布:淘宝机器人在哪 编辑:程序博客网 时间:2024/05/01 10:17

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:

1
2
3
4
5
importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpStatus;
importorg.apache.commons.httpclient.HttpException;
importorg.apache.commons.httpclient.methods.GetMethod;
importorg.apache.commons.httpclient.ConnectTimeoutException;

to

1
2
3
4
5
6
7
importorg.apache.http.client.HttpClient;
importorg.apache.http.HttpStatus;
importorg.apache.http.HttpException;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.conn.ConnectTimeoutException;
importorg.apache.http.HttpResponse;
importorg.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:

1
2
3
4
5
6
7
8
HttpClient client = newHttpClient();
GetMethod method = newGetMethod(url);
intstatusCode = client.executeMethod(method);
if(statusCode == HttpStatus.SC_OK) {
    InputStream is = method.getResponseBodyAsStream();
    // do something with the input stream
}
method.releaseConnection();

HttpClient 4.0:

1
2
3
4
5
6
7
8
HttpClient client = newDefaultHttpClient();
HttpGet method = newHttpGet(url);
HttpResponse httpResponse = client.execute(method);
intstatusCode = 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?