Monday, September 9, 2013

Understanding commons HttpClient with example.

What is HttpClient :
HttpClient is a client side  HTTP transport library whose purpose is to transmit and receive HTTP messages. The HTTP (Hyper Text Transfer Protocol ) is the most significant protocol used on the internet today. HttpClient can be used by anyone building HTTP-aware client applications such as Web Browsers , Web services clients or any system that uses HTTP protocol for distributed communication. 


HttpClient is not a browser :
Though it seems that HttpClient is simulating the functionality of a web browser , but that's not true . HttpClient is not a browser. HttpClient will not attempt to cache content, execute javascript embedded in HTML pages, try to guess content type, or reformat request / redirect location URIs.


Get Ready :

Download HttpClient dependencies and put them in the classpath of your application

or if you are a maven user , add dependency in pom :

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0</version>
</dependency>

Steps to create HttpClient :

1. Create an instance of HttpClient.
2. Create an instance of HttpMethod.
3. Tell HttpClient to execute method.
4. Read the respose.
5. Release connection.
6. Deal with the respone. 


Example : This code demonstrates how HttpClient makes a GET request to Google Server and bring back the results.
public class GoogleSearch {
     private static String searchUrl = "https://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search";

     public static void main(String[] args) {

         // Create an instance of HttpClient.
         HttpClient client = new HttpClient();

         // Create a method instance.
         GetMethod method = new GetMethod(searchUrl);

         // Provide custom retry handler.
         method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));

         try {
             // Execute the method.
             int statusCode = client.executeMethod(method);

             if (statusCode != HttpStatus.SC_OK) {
                 System.err.println("Method failed: " + method.getStatusLine());
             }

             // Read the response body.
             String responseBody = method.getResponseBodyAsString();

             // Deal with the response.
             System.out.println(responseBody);

         } catch (HttpException e) {
             System.err.println("Fatal protocol violation: " + e.getMessage());
         } catch (IOException e) {
             System.err.println("Fatal transport error: " + e.getMessage());
         } finally {
             // Release the connection.
             method.releaseConnection();
         }
     }
}

No comments :

Post a Comment