Skip to content

Instantly share code, notes, and snippets.

@davenportw15
Created July 18, 2016 00:39
Show Gist options
  • Save davenportw15/858471f5cc3c8d15b48d0b6a72e9ab32 to your computer and use it in GitHub Desktop.
Save davenportw15/858471f5cc3c8d15b48d0b6a72e9ab32 to your computer and use it in GitHub Desktop.
Async Download
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Console.WriteLine("Downloading page...");
SaveWebsite();
Console.WriteLine("Done.");
Console.ReadLine();
}
static async Task<byte[]> DownloadPageAsync()
{
HttpClient client = new HttpClient();
Uri page = new Uri("http://httpbin.org/post");
Dictionary<string, string> credentials = new Dictionary<string, string> {
{"firstname", "Test"},
{"lastname", "User"}
};
FormUrlEncodedContent formCredentials = new FormUrlEncodedContent(credentials);
HttpResponseMessage response = await client.PostAsync(page, content: formCredentials);
byte[] contents = await response.Content.ReadAsByteArrayAsync();
return contents;
}
private static async Task SaveWebsite()
{
byte[] contents = await DownloadPageAsync();
File.WriteAllBytes(path: "/Users/william/Desktop/out.html", bytes: contents);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment