Detect end of http get request header (java)

2019-07-06 20:44发布

问题:

I'm trying to create a very basic HTTP server in Java, all it needs to do is handle GET requests and reply appropriately.

I'm trying to do something like this:

  1. Read request into a buffer string
  2. Handle request
  3. Goto 1 for new requests

From what I understand, all HTTP GET request headers end with "\r\n\r\n", so I thought I could simply search the string for this character combination and if I find it, that should signify that a full request header has been sent. I'm using the code below to try to do this, unfortunately I don't seem to find the above combination. Am I mistaken in assuming that this combination should be found?

        int bytesRead = 0;
        String request = "";
        DataInputStream in = new DataInputStream(clientSocket.getInputStream());
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        while ((bytesRead = in.read(buffer)) != -1){
            request += new String(buffer).trim();
            buffer = new byte[BUFSIZE];
            if (request.contains("\r\n\r\n")) {
                handleRequest(request);
                request = "";
            }
        }

I've found detecting end of http header with \r\n\r\n and according to the answers in there I should be able to detect the end of the header this way, yet when I search a request made from my browser, it doesn't find this the "\r\n\r\n" combination. Below is the request made by Chrome:

GET / HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,              like Gecko) Chrome/51.0.2704.84 Safari/537.36
Accept:    text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4 
X-CookiesOK: I explicitly accept all cookies

Any help appreciated

Edit: This is for class, so we are not allowed to use the built in http libraries that come with java.

回答1:

Use BufferedReader.readLine(). when you get a line that is empty, you are done.



回答2:

I would personally use a BufferedReader to read line by line until I reach an empty line indicating the end of the header, it is much less error prone.

BufferedReader in = new BufferedReader(
    new InputStreamReader(clientSocket.getInputStream(), encoding)
);
String line;
StringBuilder request = new StringBuilder();
while ((line = in.readLine()) != null){
    request.append(line).append("\r\n");
    if (line.isEmpty()) {
        handleRequest(request.toString());
        break;
    }
}


标签: java http