Saturday, November 9

Asynchronous File Download from Web with C# HttpClient

Introduction: The .Net Framework provides HTTP class and with this class we can download files from the web asynchronously. Use the HttpClient class in the System.Net.Http namespace to send a GET request to a web service and retrieve the response.It was introduced with .NET 4.5 but is also available for .NET 4.0 via NuGet packages. Please see the following link for details about how to use NuGet.


The System.Net.Http.HttpClient class is used to send and receive basic requests over HTTP. It provides a base class to HTTP requests and receive HTTP responses from a resource identified by a URI. This class can be used to send a GET, PUT, POST, DELETE, and other requests to a web service. Each of these requests is sent as an asynchronous operation.
The System.Net.Http.HttpResponseMessage class represents an HTTP response message received from an HTTP request.
The System.Net.Http.HttpContent class is a base class that represents an HTTP entity body and content headers. In this case,System.Net.Http.Http.Content is used to represent the HTTP response.
The HttpResponseMessage.EnsureSuccessStatusCode method throws an exception if the web server returned an HTTP error status code.


The following code sends a request to Google map api and download an image and saves in c:\ drive. If default image viewer is installed in your machine, it will open up the map in image viewer.

using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;

namespace ConsoleApplication1
{
    ///  sends request to google map API, downloads map,opens up in viewer and saves it in local drive
   
    class Program
    {
        //google map api for Chicago,IL
        static string webAddress = "http://maps.googleapis.com/maps/api/staticmap?center=Chicago,IL&zoom=14&size=1200x1200&sensor=false";
       
        //async method to download the file
    static async void getImage()
        {

            try
            {
                //instance of HTTPClient
                HttpClient client = new HttpClient();

                //send  request asynchronously
                HttpResponseMessage response = await client.GetAsync(webAddress);
              
               // Check that response was successful or throw exception
                response.EnsureSuccessStatusCode();

                // Read response asynchronously and save asynchronously to file
                using (FileStream fileStream = new FileStream("c:\\img.png", FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //copy the content from response to filestream
                    await response.Content.CopyToAsync(fileStream);
                  

                }

                Process process = new Process();
                process.StartInfo.FileName = "c:\\img.png";
                process.Start();
            }

            catch (HttpRequestException rex)
            {
                Console.WriteLine(rex.ToString());
            }
            catch (Exception ex)
            {
                // For debugging
                Console.WriteLine(ex.ToString());
            }
        }



    static void Main(string[] args)
        {
            //call the method in main()
            getImage();

            Console.WriteLine("Hit  enter to exit...");
            Console.ReadLine();
        }
    }

}


Output:



1 comment:

priceabate said...

Thank you so much. I just could not figure out how to successfully download an image using httpclient and store it successfully locally. 3 days now I was searching the internet and finally got to your post... Thank you very much!

Post a Comment