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("");
      get.addHeader("accept", "application/xml");

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

      System.out.println("Content-Type: " +

      BufferedReader reader = new BufferedReader(new

      String line = reader.readLine();
      while (line != null) {
         line = reader.readLine();

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.