Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Created July 24, 2011 01:30
Show Gist options
  • Save prabirshrestha/1102085 to your computer and use it in GitHub Desktop.
Save prabirshrestha/1102085 to your computer and use it in GitHub Desktop.
Async/Await FluentHttp.Core Sample
private async static Task<object> HttpAsync()
{
Stream input = new MemoryStream(Encoding.UTF8.GetBytes("message=hello"));
var httpHelper = new HttpHelper("https://api.example.com");
var httpWebRequest = httpHelper.HttpWebRequest;
httpWebRequest.Method = "POST";
if (input != null)
{
try
{
httpWebRequest.ContentLength = input.Length;
using (var requestStream = await httpHelper.OpenWriteTaskAsync())
{
int read;
byte[] buffer = new byte[1024 * 4]; // 4 kb
while ((read = input.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, read);
}
}
}
catch (WebExceptionWrapper ex)
{
if (ex.GetResponse() == null)
throw;
}
finally
{
input.Dispose();
}
}
Stream responseStream = null;
WebExceptionWrapper webException = null;
try
{
responseStream = await httpHelper.OpenReadTaskAsync();
}
catch (WebExceptionWrapper ex)
{
if (ex.GetResponse() == null)
throw;
webException = ex;
}
try
{
if (webException != null)
responseStream = await httpHelper.OpenReadTaskAsync();
using (var reader = new StreamReader(responseStream))
{
try
{
return JsonSerializer.Current.DeserializeObject(reader.ReadToEnd());
}
catch (Exception ex)
{
throw webException == null ? ex : webException;
}
}
}
finally
{
if (responseStream != null)
responseStream.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment