In my prior post I walked you though how to setup WebApi in a self hosted environment. In this post we will take a look at how to consume a WebApi endpoint. We will do this by using the code from the prior example as well as by creating a new console application.
Before we get started you are going to want to create our console application and add references to the following assemblies.
- System.Json
- System.Net.Http
- System.Net.Http.Formatting
Step 1: Creating our HttpClient
When connecting to any remote endpoint there are many ways to do this, in our post we are going to use the HttpClient which is part of the System.Net.Http namespace.
var httpClient = new HttpClient();
Step 2: Connecting to our endpoint and consuming our data
Once we have our httpClient created we need to do something useful with it. The code below is what is needed in order to do exactly this.
httpClient.GetAsync( "http://localhost:8080/endpoints/episode/" )
.ContinueWith( result =>
{
var response = result.Result;
response.EnsureSuccessStatusCode();
response.Content
.ReadAsAsync<JsonArray>()
.ContinueWith( readResult =>
{
var array = readResult.Result;
foreach ( var element in array )
{
Console.WriteLine(element);
}
} );
} );
The code above is a bit much so lets take a few to break it down and take a closer look at its parts
- The first thing we are doing is using the HttpClient to connect to the our endpoint. As you can see we are doing this Async via the Task Parallel library.
- Next you should see that once we get a response from the remote endpoint we are going to handle the results via the .Result property. We will also want to ensure that the connection as valid so we should call response.EnsureSuccesStatusCode. If any status but success (200) is returned an exception will be thrown.
- Once we know we have a good connection we need to read in the content. we will read the content via the ReasAsAsync method and provide it the type of JsonArray, this tells the code how to format/deserialize the result content stream. of course you could read this as a raw stream or string but that is no fun.
- Once we have our formatted content we can do something useful with it. Of course in this example I am not converting my content into an object, I am leaving it as raw Json, but if need an object you can use the JsonSerializer to get an object.
As you can see consuming a WebApi is pretty straight forward and does involve a ton of coding or effort.
Till next time,
Posted
02-28-2012 8:35 AM
by
Derik Whittaker