深入剖析tomcat第一章

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

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值