Universal Windows Platform - Http Client

Now a days Web API is the most commonly used cloud service for any type of application. It’s flexible and easy to use. It works like normal HTTP get and post method and other advanced functionality. In this article, we’ll talk about how we can retrieve data and send data to the server via Azure Mobile Service API using HttpClient NuGet package. So, let’s get crack in HttpClient in Universal Windows Platform Application.

To make the API we’ve to go to Azure Mobile Service option. If you’ve followed my last article, that described how to create an Azure Mobile Service. Now, open your Mobile Service and navigate to the API tab.

dashboard

Now, open the Mobile Service, here we’ve named it ‘traffic’, and go to the permission tab. Make the GET & POST permission to everyone and save it.

permission

Now move to the SCRIPT tab, and past the following JavaScript code. Your code may vary due to the Table structure of your Mobile Service.

Table

Here, in GET method, we make a simple SQL query and send to the client who will request it and in POST method we’ve just send the response message ‘Hello world’, if the request made successful.

Now, create a new class and give it a name Item and initialize two property Message and Location.

  1. classItem  
  2. {  
  3.   
  4.     [JsonProperty(PropertyName = "message")]  
  5.     publicstring Message  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.   
  11.     [JsonProperty(PropertyName = "location")]  
  12.     publicstring Location   
  13.     {  
  14.         get;  
  15.         set;  
  16.     }  
  17. }  
Listing: 1

In MainPage.xaml, the design is same as the previous article. We’ve created a simple ListBox control and bind with the Table’s attribute.
  1. <ScrollViewer>  
  2.     <StackPanel Margin="10,10,0,0">  
  3.         <ListBox x:Name="listBox" Margin="10,10" RequestedTheme="Dark" FontSize="20" Background="White" Foreground="Black" BorderThickness="1" BorderBrush="Transparent">  
  4.             <ListBox.ItemContainerStyle>  
  5.                 <Style TargetType="ListBoxItem">  
  6.                     <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>  
  7.                 </Style>  
  8.             </ListBox.ItemContainerStyle>  
  9.             <ListBox.ItemTemplate>  
  10.                 <DataTemplate>  
  11.                     <Border BorderThickness="0,0,0,1" BorderBrush="#c0c0c0">  
  12.                         <StackPanel>  
  13.                             <TextBlock Foreground="Black" Text="{Binding Message}" />  
  14.                             <TextBlock Foreground="Black" Text="{Binding Location}" />  
  15.                         </StackPanel>  
  16.                     </Border>  
  17.                 </DataTemplate>  
  18.             </ListBox.ItemTemplate>  
  19.         </ListBox>  
  20.     </StackPanel>  
  21. </ScrollViewer>  
Listing: 2

Now in code behind, MainPage.xaml.cs file create a List item named _itemsList of Class Item type, and in Constructor generate a Method stub MainPage_Loaded. All the implementation is given below.
  1. privateList < Item > _itemsList = newList < Item > ();  
  2.   
  3. public MainPage()  
  4. {  
  5.     this.InitializeComponent();  
  6.     this.Loaded += MainPage_Loaded;  
  7. }  
  8.   
  9. asyncvoid MainPage_Loaded(object sender, RoutedEventArgs e)  
  10. {  
  11.     try   
  12.     {  
  13.         String uri = "_YOUR API URL GOES HERE_";  
  14.         JArray items = await GetAsync(uri);  
  15.   
  16.         int i = 0;  
  17.         int length = items.Count;  
  18.   
  19.         Debug.WriteLine(length);  
  20.   
  21.         while (i < length)   
  22.         {  
  23.             _itemsList.Add(newItem  
  24.              {  
  25.                 Message = items[i]["message"].ToString(), Location = items[i]["location"].ToString()  
  26.             });  
  27.             Debug.WriteLine(items[i]["message"].ToString() + " " + items[i]["location"].ToString()); // For testing purpose.  
  28.             i++;  
  29.         }  
  30.   
  31.         this.listBox.ItemsSource = _itemsList;  
  32.   
  33.         Item item = newItem  
  34.         {  
  35.             Message = "",  
  36.                 Location = ""  
  37.         };  
  38.   
  39.         string jsonData = JsonConvert.SerializeObject(item);  
  40.   
  41.         JObject message = await PostAsync(uri, jsonData);  
  42.         Debug.WriteLine(message); // For testing purpose.  
  43.   
  44.     } catch (Exception ex)   
  45.     {  
  46.         Debug.WriteLine(ex.Message);  
  47.     }  
  48. }  
Listing: 3

Here, first we need the API Uri, then Json Array (JArray) and get it from the given Uri. Then we get the length of the Json array and loop while it becomes zero. Inside the loop we insert the items in to the List we’ve created before and then make it the ItemSource of the ListBox.

Then we’ve created a new instance of Item class and declare two null values for POST operation. After that, we send the data to server by serializing it as a Json format. The GetAsynce and PostAsynce methods are given below.
  1. privateasyncTask < JArray > GetAsync(string uri)  
  2. {  
  3.     var httpClient = newHttpClient();  
  4.     var content = await httpClient.GetStringAsync(uri);  
  5.     returnawaitTask.Run(() => JArray.Parse(content));  
  6. }  
  7.   
  8.   
  9. publicasyncTask < JObject > PostAsync(string uri, string data)  
  10. {  
  11.     var httpClient = newHttpClient();  
  12.     var response = await httpClient.PostAsync(uri, newStringContent(data));  
  13.   
  14.     response.EnsureSuccessStatusCode();  
  15.   
  16.     string content = await response.Content.ReadAsStringAsync();  
  17.     returnawaitTask.Run(() => JObject.Parse(content));  
  18. }  
Listing: 4

These are the simple implementation of the two methods. The GetAsynce will return the Json Array from the Uri and the PostAsynce will return the success message if the data transfer done successfully. It will check if there is any error by response.EnsureSuccessStatusCode() method.

If we run the Application, it will give the same result but an attribute less than the previous article.

jam

To test your API Uri, you can use Postman Google Chrome App. This is a good way to test the Uri working or not.

history

You can view the data in different format also test the Uri by GET, POST and many other HTTP methods.

If you want to see the POST is successful or not, you can see the output windows. If you see the success message that you’ve sent from server, then you good to go.

output

This is the same message in Figure 3 which we’ve set in line number 6.

This article is for demonstration purpose, how you can use the Web API in your Universal Windows Platform Application. Hope this will help to understand the ins and outs of HttpClient Nuget package and handling JSON data. Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all