Consume Web Service Using HttpClient to POST And GET JSON Data In Windows 10 UWP

REST is a resource that implements a uniform interface using standard HTTP GET, POST, PUT methods that can be located by URI.

Windows 10 UWP supports basic get and post web requests using the following two APIs:

The System.Net.Http.HttpClient was introduced in .NET 4.5. In Windows 10 this API has changed to top layer of Windows.Web.Http.HttpClient. The supported OS and programming languages are as follows:

API OS Versions Supported Languages
System.Net.Http.HttpClient Windows Phone 8 onwards .NET languages
Windows.Web.Http.HttpClient Windows, Windows Phone 8.1 onwards All

Both of this APIs are available in UWP. Select which one you need.

If you are going to develop native UI or pass specific SSL certificates for Authentication then use Windows.Web.Http.HttpClient API.

If you are going to develop app with cross platform such as iOS, Android, then use System.Net.Http.HttpClient. This API sppports Xamarin IOS and Android development.

Now see how to consume REST service in Windows 10 app using System.Net.Http.HttpClient.

Create new windows 10 project.

For POST JSON data write the following code.

URI is the url you are going to POST JSON data.

Here, I will create runtime JSON data using dynamic and ExpandoObject, using this you can create JSON string at runtime instead of creating classes.

Json.Net are used to serialize the runtime dynamic object values to JSON data.

Create new instance for HttpClient and HttpResponseMessage.

  1. public async void POSTreq()  
  2. {  
  3.     Uri requestUri = new Uri("https://www.userauth"); //replace your Url  
  4.     dynamic dynamicJson = new ExpandoObject();  
  5.     dynamicJson.username = "[email protected]".ToString();  
  6.     dynamicJson.password = "9442921025";  
  7.     string json = "";  
  8.     json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicJson);  
  9.     var objClint = new System.Net.Http.HttpClient();  
  10.     System.Net.Http.HttpResponseMessage respon = await objClint.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));  
  11.     string responJsonText = await respon.Content.ReadAsStringAsync();  
  12. }  
For GET json response write the following code:
  1. public async void GetRequest()  
  2. {  
  3.     Uri geturi = new Uri(""); //replace your url  
  4.     System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();  
  5.     System.Net.Http.HttpResponseMessage responseGet = await client.GetAsync(geturi);  
  6.     string response = await responseGet.Content.ReadAsStringAsync();  
  7. }  
Now run the app and see the excepted out put.


Up Next
    Ebook Download
    View all
    View all