Java Reference
In-Depth Information
e.printStackTrace();
}
}
}
The
process
method is called to download a state's information. The
process
method is passed a variable, named state, that contains the code for the state that is to be
downloaded.
The
process
method begins by constructing a URL to which the XML request will
be posted.
URL url = new URL("http://www.httprecipes.com/1/10/request.php");
Next, the XML request is constructed.
String request = "<request type=\"state\"><code>"+state
+"</code></request>";
A connection is opened, and the request is posted to the web server.
URLConnection http = url.openConnection();
http.setDoOutput(true);
OutputStream os = http.getOutputStream();
os.write(request.getBytes());
InputStream is = http.getInputStream();
The response will be in XML format, as discussed earlier. Java contains many classes to sup-
port the parsing of XML. To do this, we must first create a
DocumentBuilderFactory
.
Once a
DocumentBuilderFactory
is constructed, we can pass it the
InputStream
from the HTTP connection. The XML from the
InputStream
will be
parsed and loaded into a
Document
object. The
Document
implements the Document
Object Model (DOM) for Java. As already discussed, the DOM allows Java to parse XML and
HTML.
DocumentBuilderFactory factory = DocumentBuilderFactory.newIn-
stance();
Document d = factory.newDocumentBuilder().parse(is);
The root element is obtained from the DOM.
Element e = d.getDocumentElement();
The
getXMLNode
function is called to obtain the
state
node from the XML. The
implementation of the
getXMLNode
function will be explained later in this chapter. The
getXMLAttribute
function is also called to read the
id
attribute from the
state
node.
Node stateNode = getXMLNode(e,"state");
String id = getXMLAttribute(stateNode,"id");