Saturday, October 29, 2011

RESTful Web Services: DeliciousHttpClient Example

I have been working on designing a replacement architecture for an enterprise application at work. As a result, I have been doing a lot of work with REST. The seminal work on REST is RESTful Web Services by Leonard Richardson and Sam Ruby from O'Reilly & Associates. The book is a couple of years old, but relevant today. There is only one issue with the book. There are a number of examples that do not work as expected in the current framework editions.
One such example is using Apache Commons HTTP Client. This particular framework is deprecated, and has been replaced by Apache HTTP Components.
The example code below demonstrates how to perform a RESTful call to del.ic.io.us to retrieve saved bookmarks. This is based on the application listed on page 35 of the book.
The Apache Maven based project can be downloaded here: delicious.zip.

 

DeliciousHttpClient.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.bluelotussoftware.delicious;
 
// DeliciousHttpClient.java
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
/**
 * <p>
A command-line application that fetches bookmarks from del.icio.us * and prints them to standard output.</p>
* <p>
This application is based on the work done by Leonard Richardson and Sam Ruby in the O'Reilly & Associates
 * RESTful Web Services Book.</p>
*
 * @author Leonard Richardson
 * @author Sam Ruby
 * @author John Yeary
 * @version 2.0
 */
public class DeliciousHttpClient {
 
    public static void main(String[] args)
            throws HttpException, IOException, ParserConfigurationException,
            SAXException, XPathExpressionException {
        if (args.length != 2) {
            System.out.println("Usage: java -classpath [CLASSPATH] "
                    + "DeliciousHttpClient [USERNAME] [PASSWORD]");
            System.out.println("[CLASSPATH] - Must contain commons-codec, " + "commons-logging, and commons-httpclient");
            System.out.println("[USERNAME] - Your del.icio.us username");
            System.out.println("[PASSWORD] - Your del.icio.us password");
            System.out.println();
            System.exit(-1);
        }
 
        HttpClient client = new DefaultHttpClient();
 
        // Set the authentication credentials.
        Credentials creds = new UsernamePasswordCredentials(args[0], args[1]);
        ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
 
        // Make the HTTP request.
        String url = "https://api.del.icio.us/v1/posts/recent";
        HttpGet method = new HttpGet(url);
        HttpResponse response = client.execute(method);
        InputStream responseBody = response.getEntity().getContent();
 
        // Turn the response entity-body into an XML document.
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(responseBody);
 
        client.getConnectionManager().shutdown();
 
        /*
         * Hit the XML document with an XPath expression to get the list
         * of bookmarks.
         */
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList bookmarks = (NodeList) xpath.evaluate("/posts/post", doc, XPathConstants.NODESET);
 
        // Iterate over the bookmarks and print out each one.
        for (int i = 0; i < bookmarks.getLength(); i++) {
            NamedNodeMap bookmark = bookmarks.item(i).getAttributes();
            String description = bookmark.getNamedItem("description").getNodeValue();
            String uri = bookmark.getNamedItem("href").getNodeValue();
            System.out.println(description + ": " + uri);
        }
        System.exit(0);
    }
}

0 comments :

Popular Posts