⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httprequest.java

📁 char44-5 图形Web服务器 提供了本书第4章的图形Web服务器实例的源程序;
💻 JAVA
字号:
//HttpRequest.java
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
final class HttpRequest implements Runnable
{
	final static String CRLF = "\r\n";
	Socket socket;
	JTextArea display;
	
	// 构造函数
	public HttpRequest(Socket socket, JTextArea display) throws Exception 
	{
		this.socket = socket;
		this.display = display;
	}
	public void run()
	{
		try {
            processRequest();
		} 
		catch (Exception e) {
			display.append(e + "\n");;
		}
	}
	
	private void processRequest() throws Exception {
		// 显示连接的IP地址
		display.append("Host address: " + socket.getInetAddress().getHostAddress() + "\n\n"); 
		
		// 获得套接字的输入输出流指针
		InputStream is = socket.getInputStream() ;
		DataOutputStream os = new DataOutputStream(socket.getOutputStream()) ;
		//设置输入流过滤器
		BufferedReader br = new BufferedReader(new InputStreamReader(is));;
		
		// 获得HTTP的请求信息
		String requestLine = br.readLine();
		// 显示此请求信息
		display.append("\n" + requestLine + "\n");
		
		//从请求信息中解析出文件名
		StringTokenizer tokens = new StringTokenizer(requestLine);
		String reqType = tokens.nextToken();
		boolean post = false;
		boolean fileExists = true;
		boolean commandPage = false;
		String command = "";
		FileInputStream fis = null;
		String fileName = null;
		boolean head = false;
		if(reqType.equalsIgnoreCase("POST")){
            post = true;
            fileExists = false;
            String recieved;
            int contentLength = 0;
            while ((recieved = br.readLine()) != null && recieved.length() != 0) {
				display.append(recieved + "\n");
				if(recieved.toLowerCase().startsWith("content-length:") &&
					recieved.length() > 16){
					contentLength = Integer.parseInt(recieved.substring(16));
				}
            }
            DataInputStream dis = new DataInputStream(is);
            byte[] b = new byte[contentLength];
            if(dis.read(b) != contentLength){
				throw new IOException("Complete content of POST not able to be read\n");
			};
            recieved = new String(b);
            if(recieved.toLowerCase().startsWith("command")){
				String decoded = URLDecoder.decode(recieved);
				display.append(decoded + "\n");
				if(decoded.length() > 8)
					command = decoded.substring(8);
            }
		}
		else {
            if(reqType.equalsIgnoreCase("HEAD"))
				head = true;
            fileName = tokens.nextToken();
            if(fileName.equalsIgnoreCase("/command") || fileName.equalsIgnoreCase("./command")){
				commandPage = true;
				fileExists = false;
            }
            else{
				if(fileName.startsWith("./")){
					fileName = fileName.substring(2);
				}
				fileName = "." + URLDecoder.decode(fileName);
				
				// Get and display the header lines.
				String headerLine = null;
				while ((headerLine = br.readLine()).length() !=0) {
					display.append(headerLine + "\n");
				}
				
				try {
					fis = new FileInputStream(fileName);
				} 
				catch (FileNotFoundException e) {
					fileExists = false;
				}
            }
		}
		// 构建反馈信息
		String statusLine = null;
		String contentTypeLine = null;
		String entityBody = null;
		if (fileExists) {
            statusLine = "HTTP/1.0 200 ok" + CRLF;
            contentTypeLine = "Content-type: " + 
				contentType( fileName ) + CRLF;
		} 
		else if(post){
            statusLine = "HTTP/1.0 201 ok" + CRLF;
            contentTypeLine = "text/html" + CRLF;
		}
		else if(commandPage){
            statusLine = "HTTP/1.0 200 ok" + CRLF;
            contentTypeLine = "text/html" + CRLF;
		}
		else {
            File file;
            if ((file = new File(fileName)).isDirectory()){
				statusLine = "HTTP/1.0 200 ok" + CRLF;
				contentTypeLine = "text/html" + CRLF;
				if(!head)
					entityBody = listIndex(file) + CRLF;
            }
            else{
				statusLine = "HTTP/1.0 404 Not Found" + CRLF;
				contentTypeLine = "text/html" + CRLF;
				if(!head)
					entityBody = "<HTML>" + 
					"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
					"<BODY>Sorry but the file <i>" + fileName +"</i> could not be found on this server</BODY></HTML>" + CRLF;
            }
		}
		// 发送状态行
		os.writeBytes(statusLine);
		os.writeBytes(contentTypeLine);
		// 发送空白行以表示结尾
		os.writeBytes(CRLF);
		
		
		// 发送实体
		if (fileExists && !head)	{
            sendBytes(fis, os);
            fis.close();
		}
		else if(commandPage){
            String heading = "Type system command";
            os.writeBytes("<html>\n" +
				"<head><title>" + heading + "</title></head>\n" +
				"<body>\n" + 
				"<form METHOD=POST ACTION=\"\"> \n" +
				"<strong>" + heading + "</strong><br>\n" +
				"<input name=\"command\" TYPE=text SIZE=\"60\"><p>\n" +
				"<input value=\"execute\" TYPE=submit><p>\n" +
				"</form></body>\n" + 
				"</html>\n");
		} 
		else if(post){
            String s = null;
            try {
				String recieved = new String();
				Process p = Runtime.getRuntime().exec(command);
				BufferedReader stdInput = new BufferedReader(new 
					InputStreamReader(p.getInputStream()));
				BufferedReader stdError = new BufferedReader(new 
					InputStreamReader(p.getErrorStream()));
				os.writeBytes("<html>\n" +
					"<head><title></title></head>\n" +
					"<body>\n");
				if((s = stdInput.readLine()) != null){
					os.writeBytes("Here is the output from " + command +"<br><br>\n");
					do{
						os.writeBytes(s + "<br>\n");}
					while ((s = stdInput.readLine()) != null) ;
				}
				else{
					os.writeBytes("There was no output from the command " + command + "<br><br>\n");
				}
				// 读取任何错误
				if((s = stdError.readLine()) != null){
					os.writeBytes("The command reported errors:<br><br>\n");
					do{
						os.writeBytes(s + "<br>\n");
					}
					while ((s = stdError.readLine()) != null) ;
				}
				//停止程序运行
				p.destroy();
				os.writeBytes("</body></html>\n");
            }
			catch (IOException e) {
				os.writeBytes(e + "<br>\n");
			}
		}
		else {
            os.writeBytes(entityBody);
		}
		
		// 关闭套接字及流
		os.close();
		br.close();
		socket.close();
		
      }
      private static void sendBytes(FileInputStream fis, OutputStream os) 
		  throws Exception
      {
		  // 构建1K 缓冲来存储信息 
		  byte[] buffer = new byte[1024];
		  int bytes = 0;
		  
		  // 将请求的文件复制到输出流中
		  while((bytes = fis.read(buffer)) != -1 ) {
			  os.write(buffer, 0, bytes);
		  }
      }
	  
      private static String contentType(String fileName)
      {
		  fileName = fileName.toLowerCase();
		  if(fileName.endsWith(".htm") || fileName.endsWith(".html")
			  || fileName.endsWith(".txt")) {
			  return "text/html";
		  }
		  if(fileName.endsWith(".jpg") || fileName.endsWith(".jpe")) {
			  return "image/jpeg";
		  }
		  if(fileName.endsWith(".gif")) {
			  return "image/gif";
		  }
		  return "application/octet-stream";
      }
      public String listIndex(File file){
		  String index = "";
		  String dir = file.getPath().replace('\\', '/');
		  index += "<html><head><title>" +
			  "Directory listing of " + dir +
			  "</title></head>\n\n<body>\n" ;
		  index += "<h2>Directory listing of <i>" + 
			  dir + "</i></h2><br>\n" ;
		  File list[] = file.listFiles();
		  index += "<ul>\n";
		  for(int i = 0; i < list.length; i++){
			  boolean isDir = list[i].isDirectory();
			  String name = list[i].getName();
			  index += "<li>";
			  if(isDir)
				  index += "<b>";
				  /*
				  index += "<a href = \"http://" + 
				  socket.getLocalAddress().getHostName() +
				  ":" + socket.getLocalPort() + "/" + dir + "/" + name + 
				  "\">" + name + "</a>";
			  */
			  index += "<a href = \"" + dir + "/" + name + "\">" + name + "</a>";
			  if(isDir)
				  index += "</b>";
			  index += "</li>\n" ;
		  }
		  index += "</ul>\n";
		  index += "</body></html>\n";
		  return index;
}
 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -