In this article, we learn how to use Apache HttpClient. Let’s get started.
Table of contents
Introduction to Apache HttpClient
The first version of Apache HttpClient is 4.0-alpha1, it was released at Jul 18, 2007. And nowadays, this library is still supported by Apache with the newest version - 4.5.11.
Apache HttpClient has the same functionality with HttpURLConnection is to communicate with other system based on HTTP protocol.
Spring RestTemplate and Apache HttpClient API work at different levels of abstraction.
Spring RestTemplate is superior to the HttpClient and take care of the tranformation from JSON or XML to Java objects.
The Apache HttpClient takes care of all low level details of communication via Http.
But we also can use some other http client libraries such as OkHttp, Netty.
In order to use Apache HttpClient APIs, we can add depedency into pom.xml file:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
In order to understand how to implement code by using Apache HttpClient, we can check out source code in Apache HttpClient Utils.
Benefits and Drawbacks
Large and extensive APIs
Supports cookie handling, authentication and connection management
More suitable for web browser and other web applications, because of its large size
When using in Android app, Google blog lists few bugs, we can reference to this link.
Does not support HttpResponseCache mechanism, hence leading to increased network usage and battery consumption