Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
C# Async HttpWebRequest Console POC
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment