Apache HttpClient – Tutorial And Best practices

2 Flares Twitter 0 Facebook 1 Google+ 1 LinkedIn 0 Filament.io 2 Flares ×

Overview of Apache HttpClient


HttpClient makes programmatic HTTP protocol interactions easier. It is a standards based Java implementation of Http protocols version 1.0 and 1.1. Provides complete implementation of HTTP methods – GET, POST, DELETE, PUT, HEAD, OPTIONS, TRACE). Features wise it is exhaustive.

  • Implementation of HTTP versions 1.0 and 1.1
  • Provides implementation of HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)
  • Support for HTTPS (HTTP over SSL) protocol.
  • Support for almost all popular authentication schemes- Basic, Digest, NTLM, SNPNEGO and Kerberos
  • Supports custom authentication schemes.
  • Connection management support for use in multi-threaded applications.
  • Automatic Cookie handling
  • Plug-in mechanism for custom cookie policies.
  • Uses persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
  • Provides direct access to the response code and headers sent by the server.

Note:  HttpComponents Client is a successor of and replacement for Commons HttpClient 3.x.




To work with HttpClient, download the library with all its  dependencies from http://hc.apache.org/ and add your project classpath. The starting point is the HttpClient class. There are different types of HttpClient classes, useful for different scenarios. Let us start with the basic one – DefaultHttpClient. DefaultHttpClient uses SingleClientConnManager class to handle HTTP connections.


Http Get – Using DefaultHttpClient ( Deprecated)


Above code uses DefaultHttpClient, which is deprecated. From version 4.2.x some classes, like org.apache.http.impl.client.DefaultHttpClient or org.apache.http.params.HttpParams have become deprecated.  HttpClient was never thread safe. The newer alternatives are thread safe. Hence don’t use DefaultHttpClient, there are other better ways of usage. Let us look at those.

Using CloseableHttpClient


Using Post

Working Behind a Proxy

Many times, we work behind proxies. In such situations we can configure HttpClient to work with proxies. Here is a sample configuration for the same.


Apache HttpClient-Examples

  • zingerburger

    hey !! thanks for above code but i want to use POST to send username amd submit details and then get the next pages data(parse)..how should i do it??
    I want to use both post and get