简体   繁体   中英

HTTP Sockets: Response Headers

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 with HTTP/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-length response 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 was HEAD , 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 to Receive() 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.

你的while循环永远不会执行,因为'bytes'最初为零,只有在它为正时才循环。

This is not the best way to handle HTTP. The Socket class operates on raw bytes, but HTTP headers operate on lines of text instead. You need to read lines of text in a loop until a blank line is encountered, then process the headers to decide how to finish reading the remaining raw bytes, if any. Have a look at the NetworkStream and StreamReader classes for that. A better option is to use the HttpClient client class instead, and let it handle all of these details for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM