深入剖析tomcat第一章中的代码运行有问题,静态文本发送有问题,具体代码如下:
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else {
// file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
这个地方对于静态文件发送的时候没有只是发送了文本内容,没有HTTP协议头,所以使用浏览器是无法解析的。对于这个问题可以在发送文本文件之前加上HTTP头,方法如下:
if(file.exists()){ fis = new FileInputStream(file); String headerMessage = "HTTP/1.1 200 OK\r\n"+ "Content-Type:text/html\r\n" + "\r\n" ; outputStream.write(headerMessage.getBytes()); int ch = fis.read(bytes,0,BUFFER_SIZE); while (ch != -1){ outputStream.write(bytes,0,ch); ch = fis.read(bytes,0,BUFFER_SIZE); } }