Java command-line application: build your first RESTful client

Java command-line application CREATE on exampleConnecting to a RESTful web service takes no more work than directly connecting to the service through an HTTP connection. For our first RESTful client, we'll use the command line to connect to Twitter's RESTful web service, which returns the last 20 public status updates.

Note

Twitter is a micro-blogging platform that lets multiple users update their status using 140 characters at a time. Furthermore, users can follow each other by adding other users to their network of friends. Twitter stores these updates on its servers, and by default they are publicly available, which is why we are using it in our RESTful clients.

 

Our client code is listed as follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class RESTClient {
  public static void main(String[] args) {
    try {
      URL twitter = new URL("http://twitter.com/statuses/public_timeline.xml");
      URLConnection tc = twitter.openConnection();
      BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        System.out.println(line);
      }
      in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
        }
  }
}

This is as simple as we can get, yet it's a fully-RESTful client. The first thing to note is the web service URI. The location for Twitter's API is http://twitter.com/statuses/public_timeline.xml. This is our resource's URI and points to the last 20 public status updates.

To connect to this web service, we first need to instantiate a URL object for the service's URI. Then, we open an URLConnection object for the Twitter URL instance. The method call to twitter.openConnection() executes an HTTP GET request. The lines that connect to the web service are as follows:

URL twitter = new URL("http://twitter.com/statuses/public_timeline.xml");
URLConnection tc = twitter.openConnection();

 Once we have a connection established the server returns an HTTP response. The response's payload is an XML representation of the updates. For simplicity, we opt to dump the XML payload to the standard out stream, as follows:

BufferedReader in = new BufferedReader(newInputStreamReader(tc.getInputStream()));
String line;

while ((line = in.readLine()) != null) {
      System.out.println(line);
}

 

First, we read the connection's response stream into a BufferedReader object. We then loop through each line of the stream, but first we assign it to a String object, which holds the value of each line in the stream. Subsequently, we display each line as it's read within the while loop with System.out.println(line). Finally, we enclose all our code in a try/catch statement, and we send any exception messages to the standard out stream.

Before running the application, we need to compile it with the following command:

javac RESTClient.java

To run it, we use the command:

java RESTClient

This is the first Twitter public status update from an XML structure of 20:

<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array">
    <status>
      <created_at>Mon Mar 23 23:39:06 +0000 2009</created_at>
      <id>1378638355</id>
      <text>Cricket: Dravid on the edge of history: As India securedtheir first test win on New Zealand soil in 33 yearsan..... http://ff.im/-1GAcJ</text>
      <source>&lt;ahref=&quot;http://friendfeed.com/&quot;&gt;FriendFeed&lt;/a&gt;</source>
      <truncated>false</truncated>
      <in_reply_to_status_id />
      <in_reply_to_user_id />
      <favorited>false</favorited>
      <user>
      <id>25268999</id>
      <name>all about cricket</name>
      <screen_name>allaboutcricket</screen_name>
      <description>Aggregator of Cricket News</description>
      <location></location>
      <profile_image_url>http://static.twitter.com/images/default_profile_normal.png</profile_image_url>
      <url>http://Don't have a site at the moment</url>
      <protected>false</protected>
      <followers_count>68</followers_count>
    </user>
    </status>

[19 more status elements removed]
    </statuses>

 The above result only displays one status update to save space, but we get the idea: we connect to the web service, we get a response back. We won't go into the details of the XML structure, though they are found at http://apiwiki.twitter.com/Twitter-API-Documentation.

The API's documentation tells us that if we change the .xml extension we get different resource representations. Specifically, we can change .xml to .json, .rss, or .atom. For example, if we request the updates in a JSON (JavaScript Object Notation) format, the only change we need to make to our program above is in the following line:

URL twitter = new URL("http://twitter.com/statuses/public_timeline.json");

 Again, to save space, we only show the first status update (you can get Twitter's JSON details from the API documentation):

[{"user":{"followers_count":62,"description":"","url":"http:\/\/www.facebook.com\/profile.php?id=1057301622","profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/61699483\/dorkgf5_normal.png","protected":false,"location":"New Jersey","screen_name":"CeliaTesta","name":"Celia Testa","id":16691180},"text":"@micheleeeex Lolz I don't think so. My family is all in South Jersey.","truncated":false,"favorited":false,"in_reply_to_user_id":15497704,"created_at":"Mon Mar 23 23:55:43 +0000 2009","source":"<a href=\"http:\/\/help.twitter.com\/index.php?pg=kb.page&id=75\">txt<\/a>","in_reply_to_status_id":null,"id":1378718102},...19 more status updates removed...]

 

Jakarta Commons HTTP Client

For the most part, the java.net package provides enough functionality to connect to all HTTP based services. However, the Jakarta Commons HTTP Client libraries give us granular control and easier-to-use HTTP connection objects, especially when we want to build our own, all-purpose RESTful web services tools. Therefore, lets look at how we can code our own clients using this library.

The full listing for the program using the Jakarta Commons library looks as follows:

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public class RESTWithHTTPClient {

    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        GetMethod method = newGetMethod("http://twitter.com/statuses/public_timeline.xml");

        try {
            int statusCode = client.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                System.out.println(newString(method.getResponseBody()));
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}

The result for this program is the same as previous one (the XML structure). First, we instantiate an HTTP client with the following statement:

HttpClient client = new HttpClient();

 With our client instantiated, we now proceed to create an HTTP GET method object with the following statement:

GetMethod method = new GetMethod("http://twitter.com/statuses/public_timeline.xml");

With the client and method instantiated, we now need to execute the request with:

int statusCode = client.executeMethod(method);

Note that with the Commons HTTP Client library, we have more control and can easily add error checking to our program. For example, we output the response to the standard out stream only if we get an HTTP 200 status code:

if (statusCode == HttpStatus.SC_OK) {
    System.out.println(new String(method.getResponseBody()));
}

Finally, we need to close our open connection with the statement:

method.releaseConnection();

The Commons HTTP Client library depends on two more Commons projects: Commons Codec and Commons Logging. Therefore, to compile this RESTful client, we need to include both JAR files to our classpath. Assuming our JAR files are in the same place where our Java file is located, we compile the program as follows:

javac –classpath "commons-logging-1.1.1.jar;commons-codec-1.3.jar;commons-httpclient-3.1.jar" RESTWithHTTPClient.java

To run it, we use:

java –classpath "commons-logging-1.1.1.jar;commons-codec-1.3.jar;commons-httpclient-3.1.jar" RESTWithHTTPClient

Note

When compiling this code (and subsequent code samples in my blog) in a UNIX or Linux environment, replace the character ; with :. Furthermore, you may have new JAR libraries from the ones used at the time of this writing; therefore, you may have to modify the classpath values to reflect newer versions.

 

Вас заинтересует / Intresting for you:

Getting Started with Java prog...
Getting Started with Java prog... 1621 views Doctor Thu, 02 Aug 2018, 04:05:33
Creating and Manipulating Stri...
Creating and Manipulating Stri... 1824 views Максим Николенко Sun, 10 Jun 2018, 19:17:56
Requirements of Modern Java Ap...
Requirements of Modern Java Ap... 1176 views sergejh Wed, 24 Oct 2018, 09:35:45
First Simple Java Program: ent...
First Simple Java Program: ent... 2068 views natalia Thu, 21 Jun 2018, 14:10:35
Comments (0)
There are no comments posted here yet
Leave your comments
Posting as Guest
×
Suggested Locations