Java Reference
In-Depth Information
String
[]
tokens
=
get
.
split
(
"\\s+"
);
String
method
=
tokens
[
0
];
String
version
=
""
;
if
(
method
.
equals
(
"GET"
))
{
String
fileName
=
tokens
[
1
];
if
(
fileName
.
endsWith
(
"/"
))
fileName
+=
indexFileName
;
String
contentType
=
URLConnection
.
getFileNameMap
().
getContentTypeFor
(
fileName
);
if
(
tokens
.
length
>
2
)
{
version
=
tokens
[
2
];
}
File
theFile
=
new
File
(
rootDirectory
,
fileName
.
substring
(
1
,
fileName
.
length
()));
if
(
theFile
.
canRead
()
// Don't let clients outside the document root
&&
theFile
.
getCanonicalPath
().
startsWith
(
root
))
{
byte
[]
theData
=
Files
.
readAllBytes
(
theFile
.
toPath
());
if
(
version
.
startsWith
(
"HTTP/"
))
{
// send a MIME header
sendHeader
(
out
,
"HTTP/1.0 200 OK"
,
contentType
,
theData
.
length
);
}
// send the file; it may be an image or other binary data
// so use the underlying output stream
// instead of the writer
raw
.
write
(
theData
);
raw
.
flush
();
}
else
{
// can't find the file
String
body
=
new
StringBuilder
(
"<HTML>\r\n"
)
.
append
(
"<HEAD><TITLE>File Not Found</TITLE>\r\n"
)
.
append
(
"</HEAD>\r\n"
)
.
append
(
"<BODY>"
)
.
append
(
"<H1>HTTP Error 404: File Not Found</H1>\r\n"
)
.
append
(
"</BODY></HTML>\r\n"
).
toString
();
if
(
version
.
startsWith
(
"HTTP/"
))
{
// send a MIME header
sendHeader
(
out
,
"HTTP/1.0 404 File Not Found"
,
"text/html; charset=utf-8"
,
body
.
length
());
}
out
.
write
(
body
);
out
.
flush
();
}
}
else
{
// method does not equal "GET"
String
body
=
new
StringBuilder
(
"<HTML>\r\n"
)
.
append
(
"<HEAD><TITLE>Not Implemented</TITLE>\r\n"
)
.
append
(
"</HEAD>\r\n"
)
.
append
(
"<BODY>"
)
.
append
(
"<H1>HTTP Error 501: Not Implemented</H1>\r\n"
)
.
append
(
"</BODY></HTML>\r\n"
).
toString
();
if
(
version
.
startsWith
(
"HTTP/"
))
{
// send a MIME header
sendHeader
(
out
,
"HTTP/1.0 501 Not Implemented"
,