Use the Http Head method to obtain the file length of the implementation method

  • 2020-05-10 18:46:22
  • OfStack

demand
There is a fixed URL file, which will be updated regularly by the server-side program. Now we need to write a tool to monitor the changes of this file.
The solution
The first idea I had was to download the file and see if it changed based on its size (it is known that the size of the file changes as it changes).
However, this file can sometimes be very large. If it takes a certain amount of time to download each time, I hope it can be faster.
After searching for 1, we found that Http has Head in addition to Get and Post methods, which can get http header information, where Content-Length is the size of the file.
The theory of
By setting the Method property to Head in HttpWebRequest, you can get only the header information of http without returning the actual content.
In addition to Get, Post, Head, Method properties can also be set:

Method  Property to any  HTTP 1.1  Agreement predicate: GET , HEAD , POST , PUT , DELETE , TRACE  or  OPTIONS . 

In the Http protocol, the response of the Head method is the same as that of the Get method, except that there is no body content. In other words:
Get: http header information + content
Head: http header information
This allows us to use the Head method if we only care about the http header and don't need the content.
practice

static void Main(string[] args)
{
    var url = "http://www.google.com/intl/en_ALL/images/srpr/logo1w.png";
    var len = GetHttpLength(url);
    Console.WriteLine("Url:{0}\r\nLength:{1}", url,len);
}
static long GetHttpLength(string url)
{
    var length = 0l;
    try
    {
        var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
        req.Method = "HEAD"; 
        req.Timeout = 5000; 
        var res = (HttpWebResponse)req.GetResponse();
        if (res.StatusCode == HttpStatusCode.OK)
        {
            length =  res.ContentLength;  
        }
        res.Close();
        return length;
    } 
    catch (WebException wex)
    {
        return 0;
    }
}

The output after execution is as follows:
Url:http://www.google.com/intl/en_ALL/images/srpr/logo1w.png
Length:6803
Note: the Head method is similar to the Get method 1. Sometimes the server will return the same content if the cache is set. At this point, you can add a time parameter after url to invalidate the cache to achieve real-time retrieval.
 

Related articles: