Chapter 13. RESTful Java Clients

So far, we’ve talked a lot about writing RESTful web services in Java, but we haven’t talked a lot about writing RESTful clients. The beauty of REST is that if your programming language has support for HTTP, that’s all you need. Sure, there are frameworks out there that can help you write client code more productively, but you are not required, or may not even need, to use them. Unfortunately, JAX-RS is only a server-side framework for writing actual web services. It does not provide a client API, but there is strong interest in defining one for the JAX-RS 2.0 specification. In the meantime, there are a few frameworks available that you can use to write RESTful Java clients.

java.net.URL

Like most programming languages, Java has a built-in HTTP client library. It’s nothing fancy, but it’s good enough to perform most of the basic functions you need. The API is built around two classes, java.net.URL and java.net.HttpURLConnection. The URL class is just a Java representation of a URL. Here are some of the pertinent constructors and methods:

public class URL {

   public URL(java.lang.String s)
            throws java.net.MalformedURLException {}

   public java.net.URLConnection
            openConnection() throws java.io.IOException {}
...
}

From a URL, you can create an HttpURLConnection that allows you to invoke specific requests. Here’s an example of doing a simple GET request:

URL url = new URL("http://example.com/customers/1"); connection = (HttpURLConnection) getUrl.openConnection(); ...

Get RESTful Java with JAX-RS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.