简体   繁体   中英

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?

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.

To add some code:

 url = "some web string"
 uri = new UriBuilder(url).Uri;
 request = WebRequest.Create(this.uri);
 request.Method = "HEAD";
 response = request.GetResponse();
 response.Close();

Now we've only gotten the header. Neat! Access like:

for (int i = 0; i < response.Headers.Count; ++i) {
    Console.WriteLine("\n Header Name:{0}, Value :{1}", response.Headers.Keys[i], response.Headers[i]); 
}

Unfortunately, there doesn't seem to be a way to look for specific header names in a direct way. So you'll have to use some wrapper function that checks all keys.

Edit: Execpt for, apparently, the Content Type. You can get that with response.ContentType .

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