Java Reference
In-Depth Information
}
return null;
}
public static void main(String args[]) throws TransformerException {
// Testing our RestServiceClient
RestServiceClient client = new RestServiceClient();
// Set up a transformer to properly convert an XML document to a string
Document d;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
// Test collection URL
StringWriter writer = new StringWriter();
d = client.getResourceCollection(Resource.CUSTOMER);
transformer.transform(new DOMSource(d), new StreamResult(writer));
System.out.println(writer);
// Test item URL
writer = new StringWriter();
d = client.getResourceItem(Resource.PRODUCT, 3);
transformer.transform(new DOMSource(d), new StreamResult(writer));
System.out.println(writer);
}
}
Pay particular attention to the HttpUrlConnection class used here to establish an HTTP connec-
tion and get a response from the server. This object exposes two streams using the getInputStream
and getOutputStream methods. The first enables you to get information from the server (the input),
whereas the second allows you to send information to the server (the output), which you do not
have to use here as the URL on its own is enough for the server to know which information you
want to retrieve. A short main method is added here to test the functionality of this class, using a
Transformer to convert an XML document back to a string (just using toString() will not work
for document objects). Finally, note that a BufferedReader is used together with a StringBuilder
object to quickly construct a string of the HTTP response received.
Next up, create an ObjectFactory to convert received XML replies to your Java objects:
package com.thomasbayer.sqlrest;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.thomasbayer.sqlrest.RestServiceClient.Resource;
public class ObjectFactory {
private final static RestServiceClient client = new RestServiceClient();
Search WWH ::




Custom Search