ETag in HTTP headers

Published:

One of the thing that I learned while making my app is how to optimize call to the webservice returning XML (RSS feed and the like). There is one cool feature called ETag.

Sometimes you need to know whether the RSS feed has changed, so you can make a request to pull new info. How to know without exactly requesting the XML itself.

It is very simple actually, just send HTTP request for the headers only and take note of the ETag. Then compare if the previous ETag matched with the new ETag, if it matches, then the resource doesn't change.

Here is the code in C#.

static void Main(string[] args)
{
    WebRequest webRequest = HttpWebRequest.Create("http://www.forexfactory.com/ffcal_week_this.xml");

    // Only request the headers, not the whole content
    webRequest.Method = "HEAD";
    var response = webRequest.GetResponse();

    for (int i = 0; i < response.Headers.Count; i++)
    {
        Console.WriteLine(response.Headers.Keys[i] + " : " + response.Headers[i]);
    }

    Console.Read();
}