O'Reilly logo

RESTful Java with JAX-RS 2.0, 2nd Edition 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

Chapter 16. Alternative Java Clients

While JAX-RS 2.0 added client support, there are other Java clients you can use to interact with web services if you do not have JAX-RS 2.0 available in your environment.

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) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

if (connection.getResponseCode() != 200) {
  throw new RuntimeException("Operation failed: "
                              + connection.getResponseCode());
}

System.out.println("Content-Type: " + connection.getContentType());

BufferedReader reader = new BufferedReader(new
              InputStreamReader(connection.getInputStream()));

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

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