Java Reference
In-Depth Information
{
e.printStackTrace();
}
}
/**
* Typical Java main method, create an object, and then
* call that object's go method.
*
* @param args Not used.
*/
public static void main(String args[])
{
GetCityTime module = new GetCityTime();
module.go();
}
}
This recipe uses the same extract and downloadPage functions as do the previ-
ous examples. However, the main go method is different. We will begin by examining the
go method to see how the list of cities is downloaded.
First, a URL object is constructed for the city list URL, and the entire contents are down-
loaded.
URL u = new UR("http://www.httprecipes.com/1/3/cities.php");
String str = downloadPage(u);
After the entire contents of the city list page have been downloaded, we must parse
through the HTML and find each of the cities. To begin, a count variable is created,
which holds the current city number. Secondly, a done variable is created and initialized to
false . This is demonstrated in the following lines of code:
int count = 1;
boolean done = false;
while (!done)
{
String line = extract(str, "<li>", "</a>", count);
To extract each city, the beginning and ending tokens to search between must be identi-
fied. If you examine Listing 3.4, you will see that each city is on a line between the tokens
<li> and </a> .
<li><a href="city.php?city=2">Baltimore, MD</a>
Calling the extract function with these two tokens will return Baltimore as follows:
<a href="city.php?city=2">Baltimore, MD
Search WWH ::




Custom Search