public void run() {
try {
//1 解析请求
//实例化HttpRequest,使用它来保存客户端发送过来的请求内容
HttpRequest request =new HttpRequest(socket);
HttpResponse response=new HttpResponse(socket);
//2 处理请求
//通过request获取用户浏览器地址栏中的抽象路径
String path=request.getUri();
System.out.println("抽象路径:"+path);
//测试将webapps/myweb/index.html页面回复给客户端
File enity=new File("./webapps"+path);
if(enity.exists()&&enity.isFile()){
response.setEnity(enity);
String fileName=enity.getName();
String ext=fileName.substring(fileName.lastIndexOf(".")+1);
response.putHeader("Content-Type",HttpContext.getMimeType(ext.toLowerCase()));
response.putHeader("Content-Length",fileName.length()+"");
System.out.println("资源已找到");
}else{
System.out.println("资源不存在!");
enity=new File("./webapps/root/404.html");
response.setEnity(enity);
response.setStatusCode("404");
response.setStatusReason("NotFound");
response.putHeader("Content-Type","text/html");
response.putHeader("Content-Length",enity.length()+"");
}
//3 响应客户端
response.flush();
System.out.println("读取完毕");
} finally {
try {
if(socket!=null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
该代码中第18行代码,响应头Content-Length错误,长度不够导致页面无法显示,如下图所示:
因Content-Length设置小于实际文件长度,文件数据被截断只响应了<!DOCTYPE