浏览器无法识别HTTP响应标头?

时间:2019-10-23 16:32:27

标签: java sockets http

import java.io.*;
import java.net.*;

public class WebServer{

    private void run(){
        try {
            ServerSocket serverSocket = new ServerSocket(5520);
            while(true){
                try {
                    Socket serverClient = serverSocket.accept();
                    WebServerThread wst = new WebServerThread(serverClient);
                    wst.start();
                } catch (IOException evt) {
                    System.out.println("Error");
                }
            }
        } catch (IOException evt) {
            System.out.println("error");
        }
    }

    public static void main(String[] args) {
        WebServer ws = new WebServer();
        System.out.println("Server is up and running.");
        ws.run();

    }
}
import java.io.*;
import java.net.*;
import java.lang.*;

class WebServerThread extends Thread {

    Socket serverClient;
    BufferedReader in = null;

    public WebServerThread(Socket clientSocket) {
        serverClient = clientSocket;
    }

    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(serverClient.getInputStream()));
            //System.out.println(in.readLine());
            HTTP http = new HTTP(in.readLine(), serverClient);


            in.close();
            serverClient.close();
        } catch (IOException e) {
            System.out.println("Error");
        } catch (NullPointerException e){
            System.out.println("bad");
        }


    }

}
import java.io.*;
import java.nio.Buffer;
import java.util.StringTokenizer;
import java.net.*;

public class HTTP {

    String contentTypeLine;
    String file;
    String version = "HTTP/1.1";
    //String crlf = "\\r\\n";
    String statusLine;
    String responseHeader;
    String statusCodePhrase;
    String headerFieldName = "Content-type: ";
    String headerValue;
    String header;

    public HTTP(String request, Socket socket) throws IOException {

        StringTokenizer st = new StringTokenizer(request);
        st.nextToken();
        file = "." + st.nextToken();
        try {
            BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file));
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            headerValue = contentType(file);
            statusLine = "HTML/1.0 200 OK\r\n";
            responseHeader = "Content-type: " + headerValue + "\r\n";
            dos.writeBytes(statusLine);
            dos.writeBytes(responseHeader);
            dos.writeBytes("\r\n");
            System.out.println(statusLine);
            System.out.println(responseHeader);
            System.out.println("Client requesting file: " + file);
            writeEntityBody(file, bin, dos);
            System.out.println("FIle: " + file + " sent successfully.");
        } catch (FileNotFoundException evt) {
            System.out.println(file + " not found.");
            System.out.println("Requested file does not exist.");
            statusCodePhrase = "404 Not Found";
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            dos.writeBytes("<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
                + "<BODY>Not Found</BODY></HTML>");
        } catch (IOException evt) {
            System.out.println("Bad");
       }
    }

    private void writeEntityBody(String file, BufferedInputStream bin, DataOutputStream dos) throws IOException {

        int CHUNK_SIZE = 1024;
        byte[] buffer = new byte[CHUNK_SIZE];
        int len;
        while ((len = bin.read(buffer)) != -1) {
            dos.write(buffer, 0, len);
        }
        bin.close();
        dos.flush();
        dos.close();
    }

    private String contentType(String file){

        String extension = file.split("\\.")[2];
        if(extension.equals("htm") || extension.equals("html") || extension.equals("txt")){
            contentTypeLine =  "text/html";
        }
        else if(extension.equals("jpg") || extension.equals("gif") || extension.equals("png") || extension.equals("bmp") || extension.equals("pdf")) {
            contentTypeLine =  "image/bmp";
        }
        else{
            return "application/octet-stream";
        }
        return contentTypeLine;
    }
}

基本上,我的服务器侦听来自客户端(即浏览器)的请求,因此,如果我键入"127.0.0.1:5520/test.txt",它将连接到端口5520并请求文件“ test.txt”。

就侦听请求和启动线程而言,它很好。但是在HTTP类中,当我的程序执行以下行时:

  headerValue = contentType(file);
  statusLine = "HTML/1.0 200 OK\r\n";
  responseHeader = "Content-type: " + headerValue + "\r\n";
  dos.writeBytes(statusLine);
  dos.writeBytes(responseHeader);
  dos.writeBytes("\r\n");

理想情况下,应创建标头,然后浏览器应识别标头。但是浏览器只是在编写所有这些内容,就好像它是消息正文的一部分一样。

我已经在几种不同的浏览器上尝试过,结果是:

  • IE:显示statusLine,responseHeader,就像它是消息正文的一部分一样,并显示文件的内容。

  • Firefox:抛出状态行,将responseHeader作为消息正文的一部分显示,并显示文件的内容。

  • Chrome浏览器:ERR_INVALID_HTTP_RESPONSE

我不确定为什么浏览器无法识别标题。

1 个答案:

答案 0 :(得分:2)

提示:协议称为“ HTTP”,而不是“ HTML”。