.Net Simple HTTP Client Helper Class

Recently, I have been working on a mobile app. I don’t like languages that are not C#, and I don’t have a need for low-level access, so I have been using Xamarin.Forms. Xamarin.Forms is super convenient and easy to use. Combined with Shared Projects, Xamarin.Forms allows for 95% of code to be written once and used across all major platforms. Anyways, not time for a sales pitch. My app connects to a RESTful HTTP server (henceforth known as the REST API) developed using the WebAPI framework. For the most part, this consists of getting lists of objects from the server, like a list of categories or a list of restaurants. I wrote a simple helper class for this, and would like to share part of it with you today.

Prerequisites: You will need to reference Newtonsoft.Json in your project (or in all your projects if using the shared project model).

Here is the method that can be used to ‘get’ a List of objects from the server:

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

namespace Jankcat.Helpers
{
    public static class RestHelper
    {
        public static async Task<List<T>> GetObjects<T>(Uri uri)
        {
            var client = new HttpClient();
            client.MaxResponseContentBufferSize = int.MaxValue;
            var returnobj = new List<T>();
            try
            {
                var response = await client.GetAsync(uri);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    returnobj = JsonConvert.DeserializeObject<List<T>>(content);
                }
            }
            catch
            {
                return new List<T>();
            }
            return returnobj;
        }
    }
}

To call upon this method, simply pass in a URL and the type you are expecting from the server!

var url = new Uri("http://example.com/api/whatever")
var myObject = await RestClient.GetObjects<MyType>(url);

This will return a list of whatever class you are expecting, or an empty list if the call fails. You could instead catch the exception and throw another, adding your own details, but this would be more than what I needed in this case. Feel free to use this as you want! Later I may add another method for Posting or Putting to the API, but currently I don’t have the need… so, sorry.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: