HttpClient class
provides a base class for sending/receiving the HTTP requests/responses from a
URL. It’s supported to the async feature of .NET framework.
The HttpClient is
able to process multiple concurrent requests. It’s a layer over HttpWebRequest
and HttpWebResponse.
All methods with
HttpClient are asynchronous.
Example for making
a Get/POST Request,
var
encriptedUserLogin = "hijksds@34dff@556";
var
encriptedPwd = "jsdjhll!23392mf544134";
//GET CALL
string
apiURL = "http://localhost:62028/api/Users/Authenticate";
UriBuilder builder = new
UriBuilder(apiURL);
builder.Query = "Username="+
encriptedUserLogin + "&Password="+ encriptedPwd + "";
using
(var client = new HttpClient())
{
HttpResponseMessage response =
client.GetAsync(builder.Uri).Result;
if
(response.IsSuccessStatusCode)
{
UserModel
userResult =
response.Content.ReadAsAsync<UserModel>().Result;
}
}
//POST CALL
using
(var client1 = new HttpClient())
{
var
userDataModel = new UserModel() { Username = encriptedUserLogin,
Password = encriptedPwd };
var
postTask = client1.PostAsJsonAsync<UserModel>(apiURL,
userDataModel);
postTask.Wait();
var
result = postTask.Result;
if
(result.IsSuccessStatusCode)
{
var
readTask = result.Content.ReadAsAsync<UserModel>();
readTask.Wait();
var
userRes = readTask.Result;
}
}
Model Class,
public class UserModel
{
public int
Id { get; set; }
public string
FirstName { get; set; }
public string
LastName { get; set; }
public string
Username { get; set; }
public string
Password { get; set; }
public string
Token { get; set; }
}