[英]How to Set Limit on Content Length for HttpWebResponse
我用的時候:
response = (HttpWebResponse)req.GetResponse();
它將響應來自網頁的整個HTML的包內容。 但我只想得到網頁的標題。 我可以設置響應內容長度的限制嗎?
謝謝!
如果您只需要HTTP標頭 - 請使用HEAD請求而不是GET。 如果您需要網頁的某些部分,則可能更容易閱讀整個響應,除非您知道它需要哪個部分。 您可以讀取部分響應流或使用范圍 - HttpWebRequest.AddRange 。
使用響應對象上的Headers
屬性。 在你開始閱讀它之前,只是調用GetResponse()
並不會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();
我認為此頁面上的示例涵蓋了您的需求。
例:
// 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.