Thursday, July 3, 2014

HTTPClient Class - Asynchronous and Synchronous Usage

HttpClient 

HttpClient is actually available as a NuGet package that you can download today. But a lot of the simplicity of using HttpClient comes from the new language features of C# 5. Combine these two and you got a very simple way of requesting and posting data.


Example for Synchronous -GET:

      using (var client = new HttpClient())
                {
                    var response = client.GetAsync(this.EndPoint + apiParameters).Result;
                    if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.Accepted)
                    {
                        //  performing a synchronous call
                        var responseContent = response.Content;
                        // synchronously reading the result
                        string responseString = responseContent.ReadAsStringAsync().Result;
                        return responseString;
                    }
                }


Example for Asynchronous -GET:

public async TaskGetAsync(string uri)
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(uri);

    //throw an exception if not successful
    response.EnsureSuccessStatusCode();

    string content = await response.Content.ReadAsStringAsync();
    return await Task.Run(() => JsonObject.Parse(content));

}

No comments:

Post a Comment