当我使用时:
response = (HttpWebResponse)req.GetResponse();
它将从网页回复整个HTML的包内容。但我只想得到网页的标题。我可以为响应内容长度设置限制吗?
谢谢!
答案 0 :(得分:2)
如果您只需要HTTP标头 - 请使用HEAD请求而不是GET。如果您需要网页的某些部分,则可能更容易阅读整个响应,除非您知道它需要哪个部分。您可以阅读部分响应流或使用范围 - HttpWebRequest.AddRange。
答案 1 :(得分:0)
在响应对象上使用Headers
属性。在你开始阅读之前,只是打电话给GetResponse()
并没有完全了解它。
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers.aspx
从上述网站获取的代码:
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Displays all the headers present in the response received from the URI.
Console.WriteLine("\r\nThe following headers were received in the response:");
// Displays each header and it's key associated with the response.
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i)
Console.WriteLine("\nHeader Name:{0}, Value :{1}",myHttpWebResponse.Headers.Keys[i],myHttpWebResponse.Headers[i]);
// Releases the resources of the response.
myHttpWebResponse.Close();
答案 2 :(得分:0)
我认为this page上的示例涵盖了您的需求。
示例:
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Displays all the headers present in the response received from the URI.
Console.WriteLine("\r\nThe following headers were received in the response:");
// Displays each header and it's key associated with the response.
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i)
Console.WriteLine("\nHeader Name:{0}, Value :{1}",myHttpWebResponse.Headers.Keys[i],myHttpWebResponse.Headers[i]);
// Releases the resources of the response.
myHttpWebResponse.Close();