Consuming RESTFul web Service in XamarinForms project Using HttpClient

Web service is an important part of the mobile app. 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 name of the places for a given postal code. We will use the http://api.geonames.com webservice to get the places.

Call using GET method

Now let’s create the UI having a Button and a Listview in it. Button will contain the code to fetch the web service on click event and Listview will display the result.

AppClass

We are with the UI, which is equipped with the Listview and the 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 data from the WebService. Since webservice will return JSON we will decode the JSON using the Newtonsoft.Json.

Webservice class

As mentioned above, webservice will return the JSON and we have used the DeserializeObject<>() method to deserialize the JSON to a model object. Model class would look like as:

Model

The PlaceObject class will get the array of Place class after the JSON deserization process. So we have marked the places attribute as the array name returned by the web service i.e. “postalcodes”.

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

Collectively the code looks like :

Call using POST method

To call the web service in POST method, we will replace the GetAsync() method with PostAsync() method as follows

Code for the POST method will look like

Happy coding 🙂

Categories: Cross Platform Mobile App, iOS, Visual Studio, Windows Phone, Xamarin

Leave a Reply

%d bloggers like this: