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. namespace Droid_Rest1
  3. {
  4. public class Post
  5. {
  6. public int Id { get; set; }
  7. public int UserId { get; set; }
  8. public string Title { get; set; }
  9. [JsonProperty("body")]
  10. public string Content { get; set; }
  11. public override string ToString()
  12. {
  13. return string.Format(
  14. "Post Id: {0}\nTitle: {1}\nBody: {2}",
  15. Id, Title, Content);
  16. }
  17. }
  18. }
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. namespace Droid_Rest1
  6. {
  7. [XmlRoot(ElementName = "rss")]
  8. public class Rss
  9. {
  10. [XmlElement("channel")]
  11. public Channel Channel { get; set; }
  12. }
  13. [XmlRootAttribute(ElementName = "channel")]
  14. public class Channel
  15. {
  16. [XmlElement("title")]
  17. public string Title { get; set; }
  18. [XmlElement(ElementName = "item", Type = typeof(Item))]
  19. public List<Item> Items { get; set; }
  20. }
  21. [XmlRootAttribute(ElementName = "item")]
  22. public class Item
  23. {
  24. [XmlElement("guid")]
  25. public string Guid { get; set; }
  26. [XmlElement("title")]
  27. public string Title { get; set; }
  28. [XmlElement("description")]
  29. public XmlCDataSection DescriptionCData { get; set; }
  30. public string Content
  31. {
  32. get { return WebUtility.HtmlDecode(DescriptionCData.Data); }
  33. }
  34. public override string ToString()
  35. {
  36. return string.Format(
  37. "Post Url: {0}\nTitle: {1}\nBody: {2}",
  38. Guid, Title, Content);
  39. }
  40. }
  41. }
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. namespace Droid_Rest1
  11. {
  12. [Activity(Label = "Consuming REST Services", MainLauncher = true, Icon = "@drawable/icon")]
  13. public class MainActivity : Activity
  14. {
  15. protected override void OnCreate(Bundle bundle)
  16. {
  17. base.OnCreate(bundle);
  18. SetContentView (Resource.Layout.Main);
  19. Button readJson = FindViewById<Button>(Resource.Id.readJson);
  20. Button readXml = FindViewById<Button>(Resource.Id.readXml);
  21. Button sendData = FindViewById<Button>(Resource.Id.sendData);
  22. TextView textView = FindViewById<TextView>(Resource.Id.textView);
  23. readJson.Click += async delegate
  24. {
  25. using (var client = new HttpClient())
  26. {
  27. // send a GET request
  28. var uri = "http://jsonplaceholder.typicode.com/posts";
  29. var result = await client.GetStringAsync(uri);
  30. //handling the answer
  31. var posts = JsonConvert.DeserializeObject<List<Post>>(result);
  32. // generate the output
  33. var post = posts.First();
  34. textView.Text = "First post:\n\n" + post;
  35. }
  36. };
  37. readXml.Click += async delegate
  38. {
  39. using (var client = new HttpClient())
  40. {
  41. // send a GET request
  42. var uri = "http://blog.xamarin.com/feed";
  43. var result = await client.GetStreamAsync(uri);
  44. //handling the answer
  45. var serializer = new XmlSerializer(typeof(Rss));
  46. var feed = (Rss)serializer.Deserialize(result);
  47. // generate the output
  48. var item = feed.Channel.Items.First();
  49. textView.Text = "First Item:\n\n" + item;
  50. }
  51. };
  52. sendData.Click += async delegate
  53. {
  54. using (var client = new HttpClient())
  55. {
  56. // Create a new post
  57. var novoPost = new Post
  58. {
  59. UserId = 12,
  60. Title = "My First Post",
  61. Content = "Macoratti .net - Quase tudo para .NET!"
  62. };
  63. // create the request content and define Json
  64. var json = JsonConvert.SerializeObject(novoPost);
  65. var content = new StringContent(json, Encoding.UTF8, "application/json");
  66. // send a POST request
  67. var uri = "http://jsonplaceholder.typicode.com/posts";
  68. var result = await client.PostAsync(uri, content);
  69. // on error throw a exception
  70. result.EnsureSuccessStatusCode();
  71. // handling the answer
  72. var resultString = await result.Content.ReadAsStringAsync();
  73. var post = JsonConvert.DeserializeObject<Post>(resultString);
  74. // display the output in TextView
  75. textView.Text = post.ToString();
  76. }
  77. };
  78. }
  79. }
  80. }

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.