1. 程式人生 > >使用Http Head方法獲取檔案長度

使用Http Head方法獲取檔案長度

https://blog.csdn.net/cxzhq2002/article/details/53586156

 

需求

有一個固定URL的檔案,伺服器端程式會定期的更新這個檔案,現在需要寫一個工具來監控這個檔案的變化。

 

解決辦法

最初我想到的是把這個檔案下載下來,然後通過大小來判斷檔案是否改變(已知該檔案變化時大小會變化)。

但是這個檔案有時會很大,如果每次都下載下來會消耗一定的時間,希望能更快一些。

 

搜尋了一下,發現Http除了Get和Post方法外,還有Head方法,它可以獲取http頭資訊,其中的Content-Length就是檔案的大小。

 

理論

在HttpWebRequest 中設定Method屬性為Head,就可以只獲取http的頭資訊,而不返回實際內容。

除了Get,Post,Head外,Method屬性還可以設定:

Method 屬性設定為任何 HTTP 1.1 協議謂詞:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。

在Http協議中,Head方法得到的響應和Get方法相比,除了沒有正文內容以外,其它都是一樣的。也就是說:

Get:http頭資訊+內容

Head:http頭資訊

這樣如果我們只關心http頭,而不需要內容時,就可以使用Head方法了。

 

實踐

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;
    }
}

執行後輸出如下:

Url:http://www.google.com/intl/en_ALL/images/srpr/logo1w.png 
Length:6803

 

注意:Head方法和Get方法一樣,有時候服務端設定了快取的話會返回同樣的內容回來。這時候可以在url後面增加一個時間引數使快取失效實現實時獲取.

 

參考資料

HttpWebRequest.Method 屬性

中文:http://msdn.microsoft.com/zh-cn/library/90k2e0f0(v=VS.90).aspx

英文:http://msdn.microsoft.com/en-us/library/90k2e0f0(v=VS.90).aspx

Http協議中head部分

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

 

=============================

 

9.4 HEAD

 

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

 

=========================

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)
                {
                    StringBuilder rStr = new StringBuilder();
                    var streamReader = new StreamReader(res.GetResponseStream(), Encoding.Default);//獲取響應流
                    rStr.Append(streamReader.ReadToEnd());
                    streamReader.Close();


                    length = res.ContentLength;
                }


                res.Close();
                return length;
            }
            catch (WebException wex)
            {
                return 0;
            }
        }