简体   繁体   中英

How to Set Limit on Content Length for HttpWebResponse

When I use:

   response = (HttpWebResponse)req.GetResponse();

it will respond with the package content of the entire HTML from the webpage. But I only want to get the header of the webpage. Can I set a limit for response content length?

Thanks you!

If you just need HTTP header - use HEAD request instead of GET. If you need some part of a web page it may be easier to read whole response unless you know what part of it you need. You can either read part of response stream or use range - HttpWebRequest.AddRange .

Use the Headers property on the response object. Just calling GetResponse() doesn't pull in the whole thing until you start reading it.

http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers.aspx

Code taken from the site above:

            // 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(); 

I think the examples on this page cover what you need.

Example:

// 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(); 

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