package socket;
import java.io.*;
import java.net.*;
/**
* MyHttpServer 实现一个简单的HTTP服务器端,可以获取用户提交的内容
* 并给用户一个response
* 因为时间的关系,对http头的处理显得不规范
* 对于上传附件,暂时只能解析只上传一个附件而且附件位置在第一个的情况
* **/
public class MyHttpServer {
//服务器根目录,post.html, upload.html都放在该位置
public static String WEB_ROOT = "c:/root";
//端口
private int port;
//用户请求的文件的url
private String requestPath;
//mltipart/form-data方式提交post的分隔符,
private String boundary = null;
//post提交请求的正文的长度
private int contentLength = 0;
public MyHttpServer(String root, int port) {
WEB_ROOT = root;
this.port = port;
requestPath = null;
}
//处理GET请求
private void doGet(DataInputStream reader, OutputStream out) throws Exception {
if (new File(WEB_ROOT + this.requestPath).exists()) {
//从服务器根目录下找到用户请求的文件并发送回浏览器
InputStream fileIn = new FileInputStream(WEB_ROOT + this.requestPath);
byte[] buf = new byte[fileIn.available()];
fileIn.read(buf);
out.write(buf);
out.close();
fileIn.close();
reader.close();
System.out.println("request complete.");
}
}
//处理post请求
private void doPost(DataInputStream reader, OutputStream out) throws Exception {
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
if ("".equals(line)) {
break;
} else if (line.indexOf("Content-Length") != -1) {
this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));
}
//表明要上传附件, 跳转到doMultiPart方法。
else if(line.index