You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.
O'Reilly logo

Apache HttpClient

The Apache foundation has written a nice, extendible, HTTP client library called HttpClient.[15] It is currently on version 4.0 as of the writing of this book. Although it is not JAX-RS-aware, it does have facilities for preemptive authentication and APIs for dealing with a few different media types like forms and multipart. Some of its other features are a full interceptor model, automatic cookie handling between requests, and pluggable authentication to name a few. Let’s look at a simple example:

import org.apache.http.*;
import org.apache.http.client.*;

public class MyClient {

  public static void main(String[] args) throws Exception {

      DefaultHttpClient client = new DefaultHttpClient();
      HttpGet get = new HttpGet("http://example.com/customers/1");
      get.addHeader("accept", "application/xml");

      HttpResponse response = client.execute(get);
      if (response.getStatusLine().getStatusCode() != 200) {
         throw new RuntimeExceptioin("Operation failed: " +
                   response.getStatusLine().getStatusCode());
      }

      System.out.println("Content-Type: " +
           response.getEntity().getContentType().getValue());

      BufferedReader reader = new BufferedReader(new
               InputStreamReader(response.getEntity()
                                         .getInputStream()));

      String line = reader.readLine();
      while (line != null) {
         System.out.println(line);
         line = reader.readLine();
      }
      client.getConnectionManager().shutdown();
   }
}

In Apache HttpClient 4.x, the org.apache.http.client.DefaultHttpClient class is responsible for managing HTTP connections. It handles the ...

The best content for your career. Discover unlimited learning on demand for around $1/day.