SoFunction
Updated on 2025-03-06

Detailed explanation of the implementation method of using Http Head method to obtain file length

need
There is a fixed URL file, and the server-side program will update the file regularly. Now you need to write a tool to monitor the changes in this file.
Solution
What I originally thought of was to download this file and then use the size to determine whether the file changes (it is known that the size will change when the file changes).
But this file can sometimes be very large. If you download it every time, it will take a certain amount of time, hoping it will be faster.
After searching, I found that in addition to Get and Post methods, Http also has a Head method, which can obtain http header information, and the Content-Length is the file size.
theory
Setting the Method property to Head in HttpWebRequest can only obtain the header information of http without returning the actual content.
In addition to Get, Post, and Head, the Method properties can also be set:
Copy the codeThe code is as follows:

The Method property is set to any HTTP 1.1 protocol predicate: GET, HEAD, POST, PUT, DELETE, TRACE, or OPTIONS.

In the Http protocol, the response obtained by the Head method is the same as that of the Get method except that there is no body content. That is to say:
Get: http header information + content
Head: http header information
In this way, if we only care about the http header and do not need content, we can use the Head method.
practice
Copy the codeThe code is as follows:

static void Main(string[] args)
{
    var url = "/intl/en_ALL/images/srpr/";
    var len = GetHttpLength(url);
    ("Url:{0}\r\nLength:{1}", url,len);
}
static long GetHttpLength(string url)
{
    var length = 0l;
    try
    {
        var req = (HttpWebRequest)(new Uri(url));
        = "HEAD";
        = 5000;
        var res = (HttpWebResponse)();
        if ( == )
        {
            length =  ; 
        }
        ();
        return length;
    }
    catch (WebException wex)
    {
        return 0;
    }
}

After execution, the output is as follows:
Url:/intl/en_ALL/images/srpr/
Length:6803
Notice:The head method is the same as the Get method. Sometimes the server will return the same content if the cache is set. At this time, you can add a time parameter after the url to invalidate the cache to achieve real-time acquisition.