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.
- public async void POSTreq()
- {
- Uri requestUri = new Uri("https://www.userauth"); //replace your Url
- dynamic dynamicJson = new ExpandoObject();
- dynamicJson.username = "[email protected]".ToString();
- dynamicJson.password = "9442921025";
- string json = "";
- json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicJson);
- var objClint = new System.Net.Http.HttpClient();
- System.Net.Http.HttpResponseMessage respon = await objClint.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));
- string responJsonText = await respon.Content.ReadAsStringAsync();
- }
For GET json response write the following code:
- public async void GetRequest()
- {
- Uri geturi = new Uri("http://api.openweathermap.org/data/2.5/weather?q=London"); //replace your url
- System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
- System.Net.Http.HttpResponseMessage responseGet = await client.GetAsync(geturi);
- string response = await responseGet.Content.ReadAsStringAsync();
- }
Now run the app and see the excepted out put.
Note: