Tag Archives: HTTP

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;

Sending HTTP Post Requests

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

Data is encoded as a series of key-value-pairs and then sent to the supplied url after which a response is waited for.

INCLUDES

using System.Net.Http;

POST CODE

public async void PostData()
{
    using (var client = new HttpClient())
    {
        var values = new List<KeyValuePair<string, string>>();
        values.Add(new KeyValuePair<string, string>("thing1", "hello"));
        values.Add(new KeyValuePair<string, string>("thing2 ", "world"));

        var content = new FormUrlEncodedContent(values);

        var response = await client.PostAsync("http://www.mydomain.com/recepticle.aspx", content);

        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.