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.

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, and 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 {}

            openConnection() throws {}

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("");
connection = (HttpURLConnection) url.openConnection();
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

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

Get RESTful Java with JAX-RS 2.0, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.