📄 httprequest.java
字号:
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class HttpRequest implements Runnable
{
// terminate each line of the server's response message
// with a carriage return (CR) and a line feed (LF)
final static String CRLF = "\r\n";
// store a reference to the connection socket
Socket socket;
// Constructor
public HttpRequest(Socket socket) throws Exception
{
this.socket = socket;
}
//Implement the run() method of the Runnable interface
//In order to pass an instance of the HttpRequest class to
//the Thread's constructor
public void run()
{
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private static String contentType(String fileName ){
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
};
if (fileName.endsWith(".jpg")|| fileName.endsWith(".JPG") ){
return "image/jpeg";
};
if (fileName.endsWith(".gif")|| fileName.endsWith(".GIF")){
return "image/gif";
};
if (fileName.endsWith(".mp3")|| fileName.endsWith(".wma")){
return "midi/mp3";
};
if (fileName.endsWith(".rar")|| fileName.endsWith(".zip")){
return "zip/zip";
};
return "application/octet-stream";
}
// send the file content to the soceckt
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
//This function is called from within run()
private void processRequest() throws Exception
{
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream (
socket.getOutputStream());
// Set up input stream filters.
// Create an input stream reader that chains to the socket's
// byte-oriented input stream. The input stream reader
// converts bytes read from the socket to characters. The
// conversion is based on the platform's default character
// set.
InputStreamReader isr = new InputStreamReader (is);
// Create a buffered reader that chains to the input stream
// reader. The buffered reader supplies a convenient method
// for reading entire lines of text.
BufferedReader br = new BufferedReader (isr);
//Get the request line of the HTTP request message.
String requestLine = br.readLine();
// Display the request line.
System.out.println();
System.out.println(requestLine);
/*Get and display the header lines.
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
*/
//Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
//Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
//Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 Document Follows" +CRLF;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else {
statusLine = "HTTP/1.0 200 Document Follows" + CRLF;
contentTypeLine = "Content-type: " + "text/html" + CRLF; //the response headers
/*
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
*/
/*
* the follow is the default error page http
* page, when the URL the
*/
entityBody =
"<html><head>" +
"<meta http-equiv='content-type' content='text/html;charset=utf-8'>" +
"<title>404 Not Found</title>" +
"<style><!-- "+
"body {font-family: arial,sans-serif}" +
"div.nav {margin-top: 1ex} " +
"div.nav A {font-size: 10pt; font-family: arial,sans-serif}" +
"span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}" +
"div.nav A,span.big {font-size: 12pt; color: #0000cc}" +
"div.nav A {font-size: 10pt; color: black}" +
"A.l:link {color: #6f6f6f}" +
"A.u:link {color: green}" +
"////--></style>" +
"<script><!--" +
"var rc=404;" +
"////-->" +
"</script>" +
"</head>" +
"<body text=#000000 bgcolor=#ffffff>" +
"<table border=0 cellpadding=2 cellspacing=0 width=100%><tr><td rowspan=3 width=1% nowrap>" +
"<b><font face=times color=#0039b6 size=10>S</font><font face=times color=#c41200 size=10>o</font><font face=times color=#f3c518 size=10>r</font><font face=times color=#0039b6 size=10>r</font><font face=times color=#30a72f size=10>y</font><font face=times color=#c41200 size=10> </font> </b>" +
"<td> </td></tr>" +
"<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff><b>Error</b></td></tr>" +
"<tr><td> </td></tr></table>" +
"<blockquote>" +
"<H1>Not Found</H1>" +
"The requested URL <code>/asdfasdf</code> was not found on this server." +
"<p>" +
"</blockquote>" +
"<table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor=#3366cc><img alt='' width=1 height=4></td></tr></table>" +
"</body></html>";
}
//Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
//Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
//Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody); // HTML-encoded error message will be shown
// if file not found
}
//Close streams and socket.
os.close();
br.close();
socket.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -