Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Programming with REST

Listing 2 shows a Java program that does the same thing we just did at the keyboard, but this time using Java’s URL class to connect to the Amazon.com server. The program simply sets up the URL query string and captures the resultant XML. (Be prepared to reuse this code when confronted by the chronically negative ZwiftBooks IT manager.)

Listing 2 A Java program that sends a REST styled request to an Amazon.com web service.

import java.net.*;
import java.io.*;

public class AmazonURLReader {

 public static void main(String[] args) throws Exception {

 String isbnString = "0201776413"; // Any isbn will work

 String xmlResult = executeAmazonWebService(isbnString);

 // We can do what we like with the String .. here we just print it


 // We’ll reuse this to set up our ZwiftBooks web service
 public static String executeAmazonWebService(String isbnString)
             throws Exception {

 // Set up the URL String to send to Amazon.com
 String urlString =
 " http://xml.amazon.com/onca/xml3?" +
 "t=AssociatesIDwebservices-20&dev-t=" +

 // Insert your Amazon Web Service ID here
 "xxxxxxxxxxxxxx" +

 "&AsinSearch=" + isbnString +
 "&mode=books" +

 // Create URL object to connect to Amazon.com
 URL amazonRest = new URL(urlString);

 // Use the URL instance to open a stream connection to Amazon.com
 InputStream in = amazonRest.openStream();

 int nbytes; // Bytes read from server

 // Set up buffer to hold the XML coming from Amazon.com
 byte [] buf = new byte[20000];

 int pos = 0; // Set buffer position

 // It typically takes more than one read from the Amazon.com stream
 // to fill our buffer
 while ( (nbytes = in.read(buf, pos, 1000)) != -1) {
  pos += nbytes;

  // Convert our array of bytes to a String - holds our XML
  String xmlResult = new String(buf);


 return xmlResult;

  • + Share This
  • 🔖 Save To Your Account