Xamarin Android - Consuming REST Services With HttpClient

Representational State Transfer (REST) is a Service, which is based on REST architecture to build the Services on the Web. REST requests are made in HTTP, using the same HTTP verbs that the Web Browsers use to retrieve the Web pages and send the data to the Servers. The verbs are given below.

  • GET - It is used to retrieve the data from the Web Service.
  • POST - It is used to create a new data item in the Web Service.
  • PUT - It is used to update a data item in the Web Service.
  • PATCH - It is used to update a data item in the Web Service, describing a set of instructions on how the item should be modified.
  • DELETE - It is used to delete a data item in the Web Service.

Web Service APIs that adhere to REST are called RESTful APIs and are defined using

  1. A base URL.
  2. HTTP methods, such as GET, POST, PUT, PATCH or DELETE.
  3. A media type for the data, such as JavaScript Object Notation (JSON).

The simplicity of REST has helped to make it the primary method for accessing Web services in the mobile Applications.

To show how we can consume a REST Service, I'll create a simple example that accesses REST Services available at the addresses given below.

  • http://jsonplaceholder.typicode.com/posts - Returns the data in JSON format.



  • https://blog.xamarin.com/feed/ - Returns the data in XML format.


In addition to sending the requests to get information (GET), we will also post the information using POST.

In this article, I'll perform these tasks, using the HttpClient class.

The HttpClient class is the main class used to send and receive HTTP messages through HttpRequestMessage and HttpResponseMessage. If you have previously used the WebClient and HttpWebRequest classes, you will notice that the HttpClient class has important diferences, namely

  • An HttpClient instance is used to configure the extensions, set default headers, cancel the requests and more.
  • You can issue as many requests as you want through a single HttpClient instance.
  • HttpClients are not bound to a particular HTTP or host Server. You can send any HTTP request, using the same HttpClient instance.
  • You can derive from HttpClient to create the specialized clients for the certain Websites or the standards.
  • The HttpClient class uses the new task-oriented standard (Task) to handle asynchronous requests. Thus, it makes it easier to manage and coordinate the pending requests.

The steps are given below to create the example.

Step 1

Create a new project for an Android Application
  • Open VS 2015 Community and click New Project.
  • Select Visual C# language in an Android template and Blank App (Android).
  • Enter a suitable name for your project and I'll use the name Droid_Rest1. Now, click OK button.

Step 2

Defining the layout of the application
  • Open Main.axml file in the Resources/Layout folder in Designer mode and add the controls given below from the ToolBox:
  • 3 Buttons - sendData, readJson and readXml.
  • 1 TextView - textView.

We can see the screenshot of the layout given below in Xamarin emulator.


AXML code of the layout is shown below.

Main.axml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:background="#7f6faf"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent">  
  7.     <Button  
  8.         android:text="@string/sendData"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:id="@+id/sendData" />  
  12.     <Button  
  13.         android:text="@string/readJson"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:id="@+id/readJson" />  
  17.     <Button  
  18.         android:text="@string/readXml"  
  19.         android:layout_width="match_parent"  
  20.         android:layout_height="wrap_content"  
  21.         android:id="@+id/readXml" />  
  22.     <TextView  
  23.         android:textAppearance="?android:attr/textAppearanceSmall"  
  24.         android:background="@android:color/white"  
  25.         android:textColor="@android:color/black"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content"  
  28.         android:id="@+id/textView"  
  29.         android:layout_weight="1" />  
  30. </LinearLayout>  
Setp 3
 
Defining the contents of the Strings.xml file 

Open Strings.xml file at the Resources/value folder and include the code given below.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="ApplicationName">Consuming REST Services</string>  
  4.     <string name="sendData">Send JSON</string>  
  5.     <string name="readJson">Read JSON Remote</string>  
  6.     <string    

Step 4

Including references to System.Net.Http and Newntonsoft.Json

On the Tools menu, click NuGet Package Manager and then click Manage Nuget Packages for the solution;

Select the Browse tab and type NewtonSoft. Locate the library and install it in the project.


Now, right click on the project and click Add References.

Select the Assemblies item, check the System.Net.http item and click OK.


Step 5

Creating Post and Rss classes

Let's create the Post and Rss classes, which defines the data according to the structure, which we will receive via JSON and XML.

On the Project menu, click Add class and enter the name Post. Now, enter the code given below in this class.

Post.cs

  1. using Newtonsoft.Json;  
  2.   
  3. namespace Droid_Rest1  
  4. {  
  5.     public class Post  
  6.     {  
  7.         public int Id { get; set; }  
  8.         public int UserId { get; set; }  
  9.         public string Title { get; set; }  
  10.   
  11.         [JsonProperty("body")]  
  12.         public string Content { get; set; }  
  13.   
  14.         public override string ToString()  
  15.         {  
  16.             return string.Format(  
  17.                 "Post Id: {0}\nTitle: {1}\nBody: {2}",  
  18.                 Id, Title, Content);  
  19.         }  
  20.     }  
  21. }  
In the same way, create the Rss class with the the code given below.

Rss.cs

  1. using System.Collections.Generic;  
  2. using System.Net;  
  3. using System.Xml;  
  4. using System.Xml.Serialization;  
  5.   
  6. namespace Droid_Rest1  
  7. {  
  8.     [XmlRoot(ElementName = "rss")]  
  9.     public class Rss  
  10.     {  
  11.         [XmlElement("channel")]  
  12.         public Channel Channel { get; set; }  
  13.     }  
  14.   
  15.     [XmlRootAttribute(ElementName = "channel")]  
  16.     public class Channel  
  17.     {  
  18.         [XmlElement("title")]  
  19.         public string Title { get; set; }  
  20.   
  21.         [XmlElement(ElementName = "item", Type = typeof(Item))]  
  22.         public List<Item> Items { get; set; }  
  23.     }  
  24.   
  25.     [XmlRootAttribute(ElementName = "item")]  
  26.     public class Item  
  27.     {  
  28.         [XmlElement("guid")]  
  29.         public string Guid { get; set; }  
  30.   
  31.         [XmlElement("title")]  
  32.         public string Title { get; set; }  
  33.   
  34.         [XmlElement("description")]  
  35.         public XmlCDataSection DescriptionCData { get; set; }  
  36.   
  37.         public string Content  
  38.         {  
  39.             get { return WebUtility.HtmlDecode(DescriptionCData.Data); }  
  40.         }  
  41.   
  42.         public override string ToString()  
  43.         {  
  44.             return string.Format(  
  45.                 "Post Url: {0}\nTitle: {1}\nBody: {2}",  
  46.                 Guid, Title, Content);  
  47.         }  
  48.     }  
  49. }  
Step 6
 
Defining the code in MainActivity 

Open the MainActivity file at the root of the project and include the code given below.

MainActivity.cs

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Net.Http;  
  4. using System.Text;  
  5. using System.Xml.Serialization;  
  6. using Android.App;  
  7. using Android.Widget;  
  8. using Android.OS;  
  9. using Newtonsoft.Json;  
  10.   
  11. namespace Droid_Rest1  
  12. {  
  13.     [Activity(Label = "Consuming REST Services", MainLauncher = true, Icon = "@drawable/icon")]  
  14.     public class MainActivity : Activity  
  15.     {  
  16.         protected override void OnCreate(Bundle bundle)  
  17.         {  
  18.             base.OnCreate(bundle);  
  19.   
  20.             SetContentView (Resource.Layout.Main);  
  21.             Button readJson = FindViewById<Button>(Resource.Id.readJson);  
  22.             Button readXml = FindViewById<Button>(Resource.Id.readXml);  
  23.             Button sendData = FindViewById<Button>(Resource.Id.sendData);  
  24.             TextView textView = FindViewById<TextView>(Resource.Id.textView);  
  25.   
  26.             readJson.Click += async delegate  
  27.             {  
  28.                 using (var client = new HttpClient())  
  29.                 {  
  30.                     // send a GET request  
  31.                     var uri = "http://jsonplaceholder.typicode.com/posts";  
  32.                     var result = await client.GetStringAsync(uri);  
  33.   
  34.                     //handling the answer  
  35.                     var posts = JsonConvert.DeserializeObject<List<Post>>(result);  
  36.   
  37.                     // generate the output  
  38.                     var post = posts.First();  
  39.                     textView.Text = "First post:\n\n" + post;  
  40.                 }  
  41.             };  
  42.   
  43.             readXml.Click += async delegate  
  44.             {  
  45.                 using (var client = new HttpClient())  
  46.                 {  
  47.                     // send a GET request  
  48.                     var uri = "http://blog.xamarin.com/feed";  
  49.                     var result = await client.GetStreamAsync(uri);  
  50.   
  51.                     //handling the answer  
  52.                     var serializer = new XmlSerializer(typeof(Rss));  
  53.                     var feed = (Rss)serializer.Deserialize(result);  
  54.   
  55.                     // generate the output  
  56.                     var item = feed.Channel.Items.First();  
  57.                     textView.Text = "First Item:\n\n" + item;  
  58.                 }  
  59.             };  
  60.   
  61.             sendData.Click += async delegate  
  62.             {  
  63.                 using (var client = new HttpClient())  
  64.                 {  
  65.                     // Create a new post  
  66.                     var novoPost = new Post  
  67.                     {  
  68.                         UserId = 12,  
  69.                         Title = "My First Post",  
  70.                         Content = "Macoratti .net - Quase tudo para .NET!"  
  71.                     };  
  72.   
  73.                     // create the request content and define Json  
  74.                     var json = JsonConvert.SerializeObject(novoPost);  
  75.                     var content = new StringContent(json, Encoding.UTF8, "application/json");  
  76.   
  77.                     //  send a POST request  
  78.                     var uri = "http://jsonplaceholder.typicode.com/posts";  
  79.                     var result = await client.PostAsync(uri, content);  
  80.   
  81.                     // on error throw a exception  
  82.                     result.EnsureSuccessStatusCode();  
  83.   
  84.                     // handling the answer  
  85.                     var resultString = await result.Content.ReadAsStringAsync();  
  86.                     var post = JsonConvert.DeserializeObject<Post>(resultString);  
  87.   
  88.                     // display the output in TextView  
  89.                     textView.Text = post.ToString();  
  90.                 }  
  91.             };  
  92.   
  93.         }  
  94.     }  
  95. }   

Let's understand the code.

We are using the methods given below of HttpClient class.

  • GetStringAsync - It is used to send a GET request.
  • GetStreamAsync - It is used to send a GET request.
  • PostAsync - It is used to send a POST request.

Now, we deserialize the received data, using the DeserializeObject method of the Newtonsoft class for JSON data and the Deserialize method for the XML. We will display the result in the TextView.

Running the project, using the Genymotion emulator, we will get the result given below.


Summary

In this article, we learned how to consume REST Services, using HttpClient in Xamarin with Visual Studio 2015.