Java Reference
In-Depth Information
String verb = (String) tok.nextElement();
String path = (String) tok.nextElement();
String version = (String) tok.nextElement();
if (verb.equalsIgnoreCase("GET"))
sendFile(os, path);
else
error(os, 500, "Unsupported command");
As can be seen above, the first line of the HTTP request is parsed. The first line of a
HTTP request will be something like the following form.
GET /index.html HTTP/1.1
As previously discussed in this chapter, there are three parts of this line, separated by
spaces. Using a StringTokenizer , this string can be broken into the three parts. The
verb is checked to see if it is a request other than GET . If the request is not a GET request,
then an error is displayed. Otherwise, the path is sent onto the sendFile method.
The next few sections will discuss the major methods provided in this recipe.
The Send File Method
The sendFile method is used to send a file to the web browser. This consists of a
two step process:
• Figure out the local path to the file
• Read in and transmit the file
An HTTP request will request a file path such as /images/logo.gif . This must
be translated to a local path such as c:\httproot\images\logo.gif . This trans-
formation is the first thing that the sendFile method does.
First a StringTokenizer is created to break up the path using slashes (/) as de-
limiters. This is done using the following lines of code:
// Parse the file by /'s and build a local file.
StringTokenizer tok = new StringTokenizer(path, "/", true);
System.out.println(path);
String physicalPath = addSlash(httproot);
The physicalPath variable will hold the path to the file to be transferred. A slash is
added, using the addSlash function. The physicalPath is now ready to have subdi-
rectories or files concatenated to it. The sendFile method will then parse the HTTP path
and concatenate any sub directories followed by the file requested to the physicalPath
variable. The following lines of code begin this loop:
while (tok.hasMoreElements())
{
Search WWH ::




Custom Search