C# Async HttpWebRequest Console POC

So I have to connect to an API and get some JSON.  I researched the WebRequest class.  I found that there is an option in .NET to use Async programming with this class.  So I did some research to find out that there are many ways to do the async.  The easiest is using the new keywords async and await.  See Asynchronous Programming with Async and Await (C# and Visual Basic).  

There is a full working example in the doc for GetResponse Method which is not async.

This is the working Proof of Concept (POC) that I came up with.

The GIST:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
// Assume .NET 4.5
namespace FunAPI
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is fun");
// You can't have an async main, but these async methods want to
// propogate out to main. So main has to be smart.
// See http://stackoverflow.com/questions/9208921/async-on-main-method-of-console-app
Task.WaitAll(HaveFun());
}
public static async Task HaveFun()
{
// There are 2 ways to use await. Here is the short way.
string json = await RequestParticipantAsync(37);
Console.WriteLine(json);
}
public static async Task<string> RequestParticipantAsync(int participantId)
{
var server = "1234.com";
var route = string.Format("/participant/{0}/", participantId);
var protocol = "https://";
var uri = protocol + server + route;
var accept = "application/json";
var auth = "ApiKey humma-numma-na:letters-and-numbers";
// See http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
Console.WriteLine("Request {0}", uri);
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Accept = accept;
req.Headers.Add(HttpRequestHeader.Authorization, auth);
// Build the Task
// There are 2 ways to use await. Here is the long way.
Task<WebResponse> getResponseTask = req.GetResponseAsync();
// await suspends (but not blocks) this code
// See http://msdn.microsoft.com/en-us/library/hh191443.aspx
WebResponse response = await getResponseTask;
Console.WriteLine("Content length is {0}", response.ContentLength);
Console.WriteLine("Content type is {0}", response.ContentType);
// Use the GetResponseStream to get the content
// See http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
Stream stream = response.GetResponseStream();
StreamReader readStream = new StreamReader(stream, Encoding.UTF8);
var content = readStream.ReadToEnd();
response.Close();
readStream.Close();
return content;
}
}
}
view raw FunAPI.cs hosted with ❤ by GitHub




Comments

Popular Posts