I’m practising HTTP using Sockets in C# and i’m able to get the response body with this code:
int bytes = 0;
while (bytes > 0)
{
bytes = HttpSocket.Receive(RecieveBytes, RecieveBytes.Length, 0);
Response.Body = Response.Body + Encoding.ASCII.GetString(RecieveBytes, 0, bytes);
}
When I read Response.Body it only contains HTML code. (The body).
How would I get more information? Like the response headers? I already did some googling but there’s not clear answer.
Note: I know there’s not point int creating a class or framework for HTTP in C#, since we have HttpWebRequest. However I’m doing this for learning purposes.
Swen
It can’t be true that you’re only receiving the HTTP Response body,
Socket.Receive()will receive all available bytes that the server has sent, so the response headers must be there too (if you are talking to a common web server and have issued a valid request). Use a tool like Fiddler to monitor the request-response pair and check that the response starts withHTTP/1.1 200 OK.You can call
Receive()until you’ve received a double\r\n, which indicates all headers have been sent. From there on, you’ll have to implement RFC 2616 section 4.4 to determine how much (if any) message body data to read.The most common is a
Content-lengthresponse header, which indicates how many bytes you should read after the double\r\n. If that header isn’t there (or if your request method wasHEAD, in which case you should stop reading since there won’t be a message body) and none of the other message length cases apply, you’re done reading data at this point and you should not try toReceive()any more data.But if it’s for learning purposes, you should have found the RFC and implemented that. You can’t just go read data and hope it’ll come in fine, that’s what protocols are for.