Java Reference
In-Depth Information
Next, the content-type header is checked to determine what type of file it is. If it
starts with “text”, then the file is in the “text family”, and it will be downloaded as a text file.
Otherwise, the file is downloaded as a binary file.
String type = http.getHeaderField("Content-Type").toLowerCase().
trim();
if (type.startsWith("text"))
downloadText(is, os);
else
downloadBinary(is, os);
Once the file has been downloaded, the objects are closed, and the HTTP connection
disconnected.
is.close();
os.close();
http.disconnect();
This recipe can be used anywhere you need to download the contents of a URL. It frees
the programmer of having to determine the type of file downloaded.
Recipe #4.4: Site Monitor
Bots are great at performing repetitive tasks. Probably one of the most repetitive tasks in
the world, is checking to see if a web server is still up. If a person were to perform this task,
they would sit at a computer with a stopwatch. Every minute, the user would click the refresh
button on the browser, and make sure that the web site still loaded.
Recipe 4.4 will show how to accomplish this same task, using a bot. This program will at-
tempt to connect to a web server every minute. As soon as the web server stops responding,
the program displays a message alerting the user that the web server is down. This program
is shown in Listing 4.4.
Listing 4.4: Monitor Site (MonitorSite.java)
package com.heatonresearch.httprecipes.ch4.recipe4;
import java.util.*;
import java.net.*;
import java.io.*;
public class MonitorSite
{
/**
* Scan a URL every minute to make sure it is still up.
* @param url The URL to monitor.
*/
public void monitor(URL url)
Search WWH ::




Custom Search