深入剖析tomcat第一章

来源:互联网 发布:阿里云备案幕布 psd 编辑:程序博客网 时间:2024/05/16 17:24

深入剖析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);    }}

0 0
原创粉丝点击