从我们的服务器向客户端发送HTTP响应

时间:2016-05-06 15:28:47

标签: java

我在发送http响应正文时遇到问题,我认为这行out.write(buffer, 0, bytes);中的问题请帮帮我。

    DataInputStream din = new DataInputStream(ClientConn.getInputStream());

    OutputStream ot = ClientConn.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(ot);

    String request = din.readLine().trim();
    System.out.println(request);
    StringTokenizer st = new StringTokenizer(request);

    String header = st.nextToken();
    System.out.println(header);
    if (header.equals("GET")) {
        String fileName = st.nextToken();
        String file = fileName.substring(1, fileName.length());
        System.out.println(file);
        FileInputStream fin = null;
        boolean fileExist = true;
        try {
            fin = new FileInputStream(file);
        }
        catch (Exception ex) {
            fileExist = false;
        }

        String ServerLine = "Simple HTTP Server";
        String StatusLine = null;
        String ContentTypeLine = null;
        String ContentLengthLine = null;
        String ContentBody = null;

        if (fileExist) {
            StatusLine = "HTTP/1.0 200 OK";
            ContentTypeLine = "Content-type: text/html";
            ContentLengthLine = "Content-Length: " + (new Integer(fin.available()).toString());
        } else {
            StatusLine = "HTTP/1.0 200 OK";
            ContentTypeLine = "Content-type: text/html";
            ContentBody = "<HTML>" +
                    "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
                    "<BODY>404 Not Found" +
                    "</BODY></HTML>";
            ContentLengthLine = (new Integer(ContentBody.length()).toString());
        }

        out.write(StatusLine.getBytes());
        out.write(ServerLine.getBytes());
        out.write(ContentTypeLine.getBytes());
        out.write(ContentLengthLine.getBytes());
        // output.writeUTF(file);
        if (fileExist) {

            byte[] buffer = new byte[1024];
            int bytes = 0;
            while ((bytes = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytes);

                for (int iCount = 0; iCount < bytes; iCount++) {
                    int temp = buffer[iCount];
                    System.out.print((char) temp);
                }
            }

        }

        out.flush();
        fin.close();
    } else {
        //out.write(ContentBody.getBytes());
    }

    out.close();
    ClientConn.close();

1 个答案:

答案 0 :(得分:0)

您的标头未正确写入OutputStream,您忘记在每行末尾写EOL"\r\n"个字符。在开始编写身体内容之前,您还需要编写EOL个字符。

换句话说,你需要做这样的事情:

String eol = "\r\n";
Charset charset = Charset.forName("ASCII");
byte[] eolBytes = eol.getBytes(charset);
out.write(StatusLine.getBytes(charset));
out.write(eolBytes);
out.write( ServerLine.getBytes(charset));
out.write(eolBytes);
out.write(ContentTypeLine.getBytes(charset));
out.write(eolBytes);
out.write( ContentLengthLine.getBytes(charset));
out.write(eolBytes);
// End of the header
out.write(eolBytes);
// Here the body begin

确实,您的标头必须编码为ASCII

响应更新:

有关您的代码的其他评论:

  1. 使用方法File#exists()检查文件是否存在。
  2. 使用Files.getAttribute(Paths.get("/path/to/my/file"), "size")获取文件大小
  3. 如果文件不存在,您只需在当前代码中写下正文。