Consuming Restful Web Service in Xamarin.forms Project Using Httpclient

Web Services are an important part of mobile apps. I am trying to consume a RESTFul Web Service in Xamarin using HttpClient.

Prerequisites

  • Microsoft.Net.Http
  • Newtonsoft.Json

In this example, let's display the names corresponding to a given postal code. We will use the WebService to get the data.

Call using GET method

Now let's create the UI having a Button and a ListView in it. The button will contain the code to fetch the Web Service on click event and the ListView will display the result.

Listview

We now have the UI equipped with the ListView and Button. The newButn_Clicked()method is associated with the Button click event to get the data from the Web Service. Now, let's define the code to fetch the data from the WebService. Since WebService will return JSON we will decode the JSON using Newtonsoft.Json.

webservice

As said above, WebService will return the JSON and we have used theDeserializeObject<>() method to deserialize the JSON to a model object. The Model class would look such as:

Model class

The PlaceObject class will get the array of Place classes after the JSON deserization process. So we have marked the places attribute as the array name returned by the Web Service, in other words “postalcodes”.

We can now run the code to see the data fetched from the WebService in separate platforms.

Collectively the code looks as in:

  1. using Newtonsoft.Json;  
  2. using System;  
  3. using System.Net.Http;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. namespace FeedShowingApp  
  8. {  
  9.    public class App  
  10.    {  
  11.       static ListView lstPlaces = new ListView();     
  12.       public static Page GetMainPage()  
  13.       {  
  14.          Button newButn = new Button()  
  15.          {  
  16.             Text = "Connect to Service",  
  17.          };  
  18.          newButn.Clicked += newButn_Clicked;  
  19.          lstPlaces.ItemTemplate = new DataTemplate(typeof(TextCell));  
  20.          lstPlaces.ItemTemplate.SetBinding(TextCell.TextProperty, "placeName");  
  21.          return new ContentPage  
  22.          {  
  23.             Content = new StackLayout()  
  24.             {  
  25.                Children = {  
  26.                      newButn,  
  27.                      lstPlaces  
  28.                }  
  29.             }  
  30.          };  
  31.       }  
  32.       static async void newButn_Clicked(object sender, EventArgs e)  
  33.       {  
  34.          GeoNamesWebService geoService = new GeoNamesWebService();  
  35.          Place[] places= await geoService.GetPlacesAsync();  
  36.          lstPlaces.ItemsSource = places;  
  37.       }  
  38.    }     
  39.    public class GeoNamesWebService  
  40.    {  
  41.       public GeoNamesWebService()  
  42.       {  
  43.       }  
  44.       public async Task<Place[]> GetPlacesAsync()  
  45.       {  
  46.          var client = new System.Net.Http.HttpClient();  
  47.          client.BaseAddress = new Uri("http://api.geonames.org/");  
  48.          var response = await client.GetAsync("postalCodeLookupJSON?postalcode=751010&country=IN&username=nirmalh");  
  49.          var placesJson = response.Content.ReadAsStringAsync().Result;  
  50.          Placeobject placeobject = new Placeobject();  
  51.          if(placesJson!="")  
  52.          {  
  53.             placeobject = JsonConvert.DeserializeObject<Placeobject>(placesJson);  
  54.          }  
  55.          return placeobject.places;  
  56.       }  
  57.    }  
  58.    
  59.    public class Placeobject  
  60.    {  
  61.       [JsonProperty("postalcodes")]  
  62.       public Place[] places { getset; }  
  63.    }  
  64.      
  65.    public class Place  
  66.    {  
  67.       public string placeName { getset; }  
  68.    }  
  69. }  
Call using POST method

To call the Web Service in the POST method, we will replace the GetAsync() method with the PostAsync() method as follows:
  1. StringContent str = new StringContent("postalcode=751010&country=IN&username=nirmalh", Encoding.UTF8, "application/x-www-form-urlencoded");  
  2. var response = await client.PostAsync(new Uri("http://api.geonames.org/postalCodeLookupJSON"), str);  
The code for the POST method will look like:
  1. using Newtonsoft.Json;  
  2. using System;  
  3. using System.Net.Http;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. namespace FeedShowingApp  
  8. {  
  9.       public class App  
  10.       {  
  11.          static ListView lstPlaces = new ListView();  
  12.          public static Page GetMainPage()  
  13.          {  
  14.             Button newButn = new Button()  
  15.             {  
  16.                Text = "Connect to Service",  
  17.             };  
  18.             newButn.Clicked += newButn_Clicked;  
  19.             lstPlaces.ItemTemplate = new DataTemplate(typeof(TextCell));  
  20.             lstPlaces.ItemTemplate.SetBinding(TextCell.TextProperty, "placeName");  
  21.             return new ContentPage  
  22.             {  
  23.                Content = new StackLayout()  
  24.                {  
  25.                   Children = {  
  26.                         newButn,  
  27.                         lstPlaces  
  28.                   }  
  29.                }  
  30.             };  
  31.       }  
  32.    
  33.       static async void newButn_Clicked(object sender, EventArgs e)  
  34.       {  
  35.          GeoNamesWebService geoService = new GeoNamesWebService();  
  36.          Place[] places= await geoService.GetPlacesAsync();  
  37.          lstPlaces.ItemsSource = places;  
  38.       }  
  39.    }  
  40.    
  41.    
  42.    public class GeoNamesWebService  
  43.    {  
  44.       public GeoNamesWebService()  
  45.       {  
  46.       }  
  47.       public async Task<Place[]> GetPlacesAsync()  
  48.       {  
  49.          var client = new System.Net.Http.HttpClient();  
  50.          client.BaseAddress = new Uri("http://api.geonames.org/");  
  51.          StringContent str = new StringContent("postalcode=752020&country=IN&username=nirmalh", Encoding.UTF8, "application/x-www-form-urlencoded");  
  52.          var response = await client.PostAsync(new Uri("http://api.geonames.org/postalCodeLookupJSON"), str);  
  53.          var placesJson = response.Content.ReadAsStringAsync().Result;  
  54.          Placeobject placeobject = new Placeobject();  
  55.          if(placesJson!="")  
  56.          {  
  57.             placeobject = JsonConvert.DeserializeObject<Placeobject>(placesJson);  
  58.          }  
  59.          return placeobject.places;  
  60.       }  
  61.    }  
  62.    
  63.    
  64.    public class Placeobject  
  65.    {  
  66.       [JsonProperty("postalcodes")]  
  67.       public Place[] places { getset; }  
  68.    }  
  69.    public class Place  
  70.    {  
  71.       public string placeName { getset; }  
  72.    }  
  73. }  
Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all