Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HTTP Post and read only response's headers before fetching body

I'm doing something like this:

 var httpWebRequest = WebRequest.Create(context.Url) as HttpWebRequest;
 httpWebRequest.Method = "POST"
 ... (set all the stuff)
 ... (get request stream and post data)

 //Get response
 var httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;

 ... (Inspect Headers)

 //Get response stream and read body
 var responseStream = httpWebRequest.GetResponseStream();

On my humble expectations I thought that calling GetResponse() would fetch only headers and body would be actually downloaded when I start reading from the response stream. What actually happens is that when I call the GetResponseStream() and read it, data is already available. Response is ordinary HTML page. I believe with chunked data it works well.

So my question is, what's really happening there and how to get only headers from a http post before fetching the body's content?

like image 327
Israel Lot Avatar asked Jan 31 '26 16:01

Israel Lot


1 Answers

With GET or POST requests, the server will send all the response data without separation of headers and 'body' in transmissions. To get only the headers set httpWebRequest.Method to "HEAD" and use httpWebResponse.Headers ( http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers.aspx ) to gather header data.

like image 157
Skonen Avatar answered Feb 03 '26 06:02

Skonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!