Tag Archives: Caching

Sending HTTP Get Requests

Sometimes you may need to retrieve data from a webserver, one of the ways to do this is by using HTTP Get. C# offers the HTTPClient class to make this process relatively simple.

INCLUDES

using System.Net.Http;

GET CODE

public async void GetData()
{
    using (var client = new HttpClient())
    {
        var response = await client.GetAsync(url);

        var responseString = await response.Content.ReadAsStringAsync();
    }
}

NOTES

The HTTPClient class is not available for all version of Visual Studio or the .Net framework. It should work natively in Visual Studio 12 and 13 for the .Net framework versions 4.5 and above. A portable version is available on NuGet for other platforms such as Windows phone 7.1 and 8.0.

Sometimes caching of requests can mean that calls using HTTP Get result in the same data being returned each time, even though the data that is being requested has changed. This is particularly evident on the Windows Phone but can be fixed by setting the IfModifiedSince Property on the HTTPClient. The code below simply says that any data modified up to the current time should be returned.

client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;