Note: This blog has been moved to http://blog.yuvisense.net

Monday, April 10, 2006

[Tech]Finding Size of a HTTP Resource in 4 Lines of VB.NET Code..

Well, my First coding Tech Post. And, Here are the four lines of code that get you just the size of a HTTP Resource, without the content. A HTTP Resource is just any file which is available over HTTP.

Dim wr As Net.HTTPWebRequest = _
Net.HTTPWebRequest.Create("http://yuvipanda.blogspot.com")
wr.Method = "HEAD"
Dim wresp As Net.HTTPWebResponse = wr.GetResponse
MsgBox(wresp.ContentLength / 1024)

That's it! Running it would give you the size of my Blog Home Page in Kilobytes. Here's a rundown of each line of code:

Line 1: I create a HTTPWebRequest object that points to the http://yuvipanda.blogspot.com page.

Line 2: Most important line. HTTP methods instruct the HTTP server to perform certain actions on the specified Resource. For example, the most common method, GET, just retrieves the given Resource, while the HEAD methods retrieves only the Headers of the response. Headers contain important information about the content of the response being sent back, such as it's length, type, last modified date, etc.. Also, you can also access all the Headers through the Headers collection of the Headers property of Response.

Line 3: We just send the Request and get the Response for it.

Line 4: We get the ContentLength property of the Response object, which gives the Length of the Resource in Bytes. We divide by 1024 to convert it to Kilobytes. And, use msgbox to display it to the user!

So, It's simple as that! Learnt it from the HTTP 1.1 Specs, which are quite well written. Get them here. If a worthless 1 5 year old like me can understand them, you too can:D

P.S. I asked Aswin if he knew how to do it, and he gave me a roundabout way of opening a socket, sending a GET request and aborting the socket after you get the Content-Length header. Not the way a VB.NET developer does it:D I'm such a Weasel:D I'm so proud, I beat a great VB.NET Developer....

2 Comments:

Blogger Aswin Anand T.H. said...

ha ha!!

4/10/2006 07:18:00 AM  
Blogger Aswin Anand T.H. said...

btw, who told im great??

4/10/2006 07:19:00 AM  

Post a Comment

<< Home