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.
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.
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:
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:
- using Newtonsoft.Json;
- using System;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
- using Xamarin.Forms;
- namespace FeedShowingApp
- {
- public class App
- {
- static ListView lstPlaces = new ListView();
- public static Page GetMainPage()
- {
- Button newButn = new Button()
- {
- Text = "Connect to Service",
- };
- newButn.Clicked += newButn_Clicked;
- lstPlaces.ItemTemplate = new DataTemplate(typeof(TextCell));
- lstPlaces.ItemTemplate.SetBinding(TextCell.TextProperty, "placeName");
- return new ContentPage
- {
- Content = new StackLayout()
- {
- Children = {
- newButn,
- lstPlaces
- }
- }
- };
- }
- static async void newButn_Clicked(object sender, EventArgs e)
- {
- GeoNamesWebService geoService = new GeoNamesWebService();
- Place[] places= await geoService.GetPlacesAsync();
- lstPlaces.ItemsSource = places;
- }
- }
- public class GeoNamesWebService
- {
- public GeoNamesWebService()
- {
- }
- public async Task<Place[]> GetPlacesAsync()
- {
- var client = new System.Net.Http.HttpClient();
- client.BaseAddress = new Uri("http://api.geonames.org/");
- var response = await client.GetAsync("postalCodeLookupJSON?postalcode=751010&country=IN&username=nirmalh");
- var placesJson = response.Content.ReadAsStringAsync().Result;
- Placeobject placeobject = new Placeobject();
- if(placesJson!="")
- {
- placeobject = JsonConvert.DeserializeObject<Placeobject>(placesJson);
- }
- return placeobject.places;
- }
- }
-
- public class Placeobject
- {
- [JsonProperty("postalcodes")]
- public Place[] places { get; set; }
- }
-
- public class Place
- {
- public string placeName { get; set; }
- }
- }
Call using POST methodTo call the Web Service in the POST method, we will replace the GetAsync() method with the PostAsync() method as follows:
- StringContent str = new StringContent("postalcode=751010&country=IN&username=nirmalh", Encoding.UTF8, "application/x-www-form-urlencoded");
- var response = await client.PostAsync(new Uri("http://api.geonames.org/postalCodeLookupJSON"), str);
The code for the POST method will look like:
- using Newtonsoft.Json;
- using System;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
- using Xamarin.Forms;
- namespace FeedShowingApp
- {
- public class App
- {
- static ListView lstPlaces = new ListView();
- public static Page GetMainPage()
- {
- Button newButn = new Button()
- {
- Text = "Connect to Service",
- };
- newButn.Clicked += newButn_Clicked;
- lstPlaces.ItemTemplate = new DataTemplate(typeof(TextCell));
- lstPlaces.ItemTemplate.SetBinding(TextCell.TextProperty, "placeName");
- return new ContentPage
- {
- Content = new StackLayout()
- {
- Children = {
- newButn,
- lstPlaces
- }
- }
- };
- }
-
- static async void newButn_Clicked(object sender, EventArgs e)
- {
- GeoNamesWebService geoService = new GeoNamesWebService();
- Place[] places= await geoService.GetPlacesAsync();
- lstPlaces.ItemsSource = places;
- }
- }
-
-
- public class GeoNamesWebService
- {
- public GeoNamesWebService()
- {
- }
- public async Task<Place[]> GetPlacesAsync()
- {
- var client = new System.Net.Http.HttpClient();
- client.BaseAddress = new Uri("http://api.geonames.org/");
- StringContent str = new StringContent("postalcode=752020&country=IN&username=nirmalh", Encoding.UTF8, "application/x-www-form-urlencoded");
- var response = await client.PostAsync(new Uri("http://api.geonames.org/postalCodeLookupJSON"), str);
- var placesJson = response.Content.ReadAsStringAsync().Result;
- Placeobject placeobject = new Placeobject();
- if(placesJson!="")
- {
- placeobject = JsonConvert.DeserializeObject<Placeobject>(placesJson);
- }
- return placeobject.places;
- }
- }
-
-
- public class Placeobject
- {
- [JsonProperty("postalcodes")]
- public Place[] places { get; set; }
- }
- public class Place
- {
- public string placeName { get; set; }
- }
- }
Happy coding.