Java Reference
In-Depth Information
Do you see the cities in the above HTML? Find the <li> tags and you will find the cit-
ies. Each of these city lines link to the city.php page. For example, to display Baltimore's
time, you would access the following URL:
http://www.httprecipes.com/1/3/city.php?city=2
This recipe will access the city list page to obtain a list of cities. Then that list will be used
to build a second list that will contain the times for each of those cities. You can see Recipe
3.3 in Listing 3.5.
Listing 3.5: Get the Time for Select Cities (GetCityTime.java)
package com.heatonresearch.httprecipes.ch3.recipe3;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
public class GetCityTime
{
// the size of a buffer
public static int BUFFER_SIZE = 8192;
/**
* This method downloads the specified URL into a Java
* String. This is a very simple method, that you can
* reused anytime you need to quickly grab all data from
* a specific URL.
*
* @param url The URL to download.
* @return The contents of the URL that was downloaded.
* @throws IOException Thrown if any sort of error occurs.
*/
public String downloadPage(URL url) throws IOException
{
StringBuilder result = new StringBuilder();
byte buffer[] = new byte[BUFFER_SIZE];
InputStream s = url.openStream();
int size = 0;
do
{
size = s.read(buffer);
if (size != -1)
result.append(new String(buffer, 0, size));
Search WWH ::




Custom Search