O'Reilly logo

RESTful Java with JAX-RS by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required