Calling WebAPI using HttpClient


 

What is HttpClient?

  • A WebAPI REST friendly client.
  • An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.
  • You can issue as many requests as you like through a single HttpClient instance.
  • HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance. i.e. no CORS restriction.
  • You can derive from HttpClient to create specialized clients for particular sites or patterns
  • HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.

Setup

Install-Package Microsoft.AspNet.WebApi.Client

HTTP GET
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(“
http://localhost:9000/”);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json“));

    HttpResponseMessage response = await client.GetAsync(“api/products/1”);
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync>Product>();
        Console.WriteLine(“{0}\t${1}\t{2}”, product.Name, product.Price, product.Category);
    }
}

If the status code in the response is a success code, the response body contains the JSON representation of a product. Call ReadAsAsync to deserialize the JSON payload to a Product instance. The ReadAsync method is asynchronous because the response body can be arbitrarily large.

A note about error handling: HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code.

If you prefer to treat HTTP error codes as exceptions, call the EnsureSuccessStatusCode method. This method throws an exception if the response status is not a success code:

try
{
    HttpResponseMessage response = await client.GetAsync(“api/products/1”);
    resp.EnsureSuccessStatusCode();    // Throw if not a success code.
    // …
}
catch (HttpRequestException e)
{
}

HTTP POST
Uri gizmoUrl;
var gizmo = new Product() { Name = “Gizmo”, Price = 100, Category = “Widget” };
response = await client.PostAsJsonAsync(“api/products”, gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    gizmoUrl = response.Headers.Location;
}

HTTP PUT
gizmo.Price = 80;   // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);

HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);

Reference: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

http://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx

Advertisements

One thought on “Calling WebAPI using HttpClient

  1. This is just a bad copy of the Microsoft documentation. One thing you could actually do is have an example of the JSON returned by response.Content.ReadAsAsync>Product>();

    If you try this sample with any other REST Service, which has similar structure, it doesn’t work.have you seen this example working?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s