简体   繁体   English

C#HTTP在获取正文之前发布并只读取响应的标题

[英]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. 根据我的谦卑期望,我认为调用GetResponse()只会获取标题,当我开始从响应流中读取时,实际上会下载正文。 What actually happens is that when I call the GetResponseStream() and read it, data is already available. 实际发生的是当我调用GetResponseStream()并读取它时,数​​据已经可用。 Response is ordinary HTML page. 响应是普通的HTML页面。 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? 所以我的问题是,那里真正发生了什么以及如何在获取正文内容之前从http帖子中获取标题?

With GET or POST requests, the server will send all the response data without separation of headers and 'body' in transmissions. 使用GET或POST请求,服务器将发送所有响应数据,而不会在传输中分离标头和“正文”。 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. 要只获取标题,请将httpWebRequest.Method设置为“HEAD”并使用httpWebResponse.Headers( http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers.aspx )来收集标题数据。

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 . 你可以使用response.ContentType来获得它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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