Translate

Wednesday, January 28, 2015

C# Simple HttpClient Console application

In this example we will get content from google.com using the System.Net.Http.HttpClient class

Create a new .net console app in Visual Studio 2012. Add a reference to System.Net.http.dll (.net version 4.0)



Copy paste the code below.

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace HttpClientTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var httpClient = new HttpClient();

            Task asyncThread = httpClient.GetAsync(
                "https://www.google.com").
                ContinueWith(taskWithResponse =>
                {
                    HttpResponseMessage response = taskWithResponse.Result;
                    Task<string> readTask = response.Content.ReadAsStringAsync();

                    Console.WriteLine(readTask.Result);
                }
                );

            asyncThread.Wait();
        }
    }

}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator