Friday, April 12, 2019

Smallest example I could think of using C# Async/Await and HttpClient.GetAsync() with Generics

Smallest example I could think of using HttpClient.GetAsync() with Generics.


using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace AsyncHttpClient
{
    /// <summary>
    /// Tiny example of using HttpClient.GetAsync() with Generics.
    /// Uses the REST API calls from the most excellent mysafeinfo.com for presidents and Beatles albums
    /// This prints:
    /// Requesting presidents
    /// Requesting Beatles albums
    /// ... waiting ...
    /// first president = number: '1','', party: '', term: ''
    /// first Beatles album = album name: 'Please Please Me (Mono)', date: '1963-03-22T00:00:00'
    /// </summary>
    public class President
    {
        public int president;
        public string name, party, term;
        public override string ToString() { return $"number: '{president}','{name}', party: '{party}', term: '{term}'"; }
    }
    public class BeatlesAlbum
    {
        public string album, date;
        public override string ToString() { return $"album name: '{album}', date: '{date}'"; }
    }

    class AsyncHttpClientExample
    {
         private static void Main()
        {
            string presidentsUrl = "https://mysafeinfo.com/api/data?list=presidents&format=json";
            string beatlesUrl = "https://mysafeinfo.com/api/data?list=beatlesalbums&format=json&select=ent,typ,rd&alias=ent=artist,typ=album,rd=date";
            var asyncHttpClientExample = new AsyncHttpClientExample();
            Console.Out.WriteLine("Requesting presidents");
            var presidents = asyncHttpClientExample.GetAsync<List<President>>(presidentsUrl);
            Console.Out.WriteLine("Requesting Beatles albums");
            var albums = asyncHttpClientExample.GetAsync<List<BeatlesAlbum>>(beatlesUrl);
            Console.Out.WriteLine("... waiting ...");
            Console.Out.WriteLine("first president = {0}", presidents.Result[0]);
            Console.Out.WriteLine("first Beatles album = {0}", albums.Result[0]);
        }
        private async Task<T> GetAsync<T>(string url)
        {
            HttpClient client = new HttpClient(new HttpClientHandler());
            HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
            var jsonString = response.Content.ReadAsStringAsync().Result;
            T result = JsonConvert.DeserializeObject<T>(jsonString);

            return result;
        }
    }
}

No comments: