How can I send an HTTP Response using only standard network libraries?

前端 未结 3 402
旧时难觅i
旧时难觅i 2021-01-26 15:17

I\'m working on my first homework project in a web programming class, which is to write a simple web server in Java. I\'m at the point where I have data being transmitted back a

3条回答
  •  不思量自难忘°
    2021-01-26 15:43

    Edit It looks to me like in the 404 situation, you're sending something like this:

    HTTP/1.1 404 Not Found
    Content-Type: text/html
    HTTP/1.1 200 OK
    Content-Length: 1234
    Content-Type: text/html
    

    ...followed by the 404 page. Note the 200 line following the 404. This is because your 404 handling is calling sendFile, which is outputting the 200 response status code. This is probably confusing the receiver.

    Old answer that missed that:

    An HTTP response starts with a status line followed (optionally) by a series of headers, and then (optionally) includes a response body. The status line and headers are just lines in a defined format, like (to pick a random example):

    HTTP/1.0 404 Not Found
    

    To implement your small HTTP server, I'd recommend having a read through the spec and seeing what the responses should look like. It's a bit of a conceptual leap, but they really are just lines of text returned according to an agreed format. (Well, it was a conceptual leap for me some years back, anyway. I was used to environments that over-complicated things.)

    It can also be helpful to do things like this from your favorite command line:

    telnet www.google.com 80
    GET /thispagewontbefound
    

    ...and press Enter. You'll get something like this:

    HTTP/1.0 404 Not Found
    Content-Type: text/html; charset=UTF-8
    X-Content-Type-Options: nosniff
    Date: Sun, 12 Sep 2010 23:01:14 GMT
    Server: sffe
    Content-Length: 1361
    X-XSS-Protection: 1; mode=block
    

    ...followed by some HTML to provide a friendly 404 page. The first line above is the status line, the rest are headers. There's a blank line between the status line/headers and the first line of content (e.g., the page).

提交回复
热议问题