I just start learning socket programming with Java and I already encountered an unusual behavior. Here's the code snippet
writer.println("GET " + path + " " + protocol);
//writer.println();
writer.println("Host: " + hostname);
writer.println();
writer.flush();
This will give me "301 Moved Permanently" code with both HTTP 1.1 and 1.0. If I uncomment the empty line between the request and host name
writer.println("GET " + path + " " + protocol);
writer.println();
writer.println("Host: " + hostname);
writer.println();
writer.flush();
It would give me "HTTP/1.1 400 Bad Request" for HTTP 1.1 and "HTTP/1.1 200 OK" for HTTP 1.0.
Why does it have such behavior? Does this happen because we have the request in HTTP 1.0 and the response is in HTTP 1.1?
Thanks.
HTTP status code 301 is a redirect to a new URL:
The server is telling you that the URL you sent your
GETrequest to is no longer valid. You need to extract the value of theLocationheader from the server's response and then repeat the same request to the specified URL.The
Hostheader is optional in HTTP 1.0 but is required in HTTP 1.1:So, when you do not insert the extra blank line, you end up sending these requests separately:
Which are both valid.
But, when you insert the extra blank line, you are actually sending two separate requests at one time:
The request headers and request body are separated by a blank line, and a
GETrequest does not have a request body, so the first blank line ends the request.So, in this case, the first request is valid only for HTTP 1.0 and is invalid for HTTP 1.1 because the
Hostheader is missing. The second request is just plain invalid in either version.