@manhng

Welcome to my blog!

Test API with HttpClient

October 9, 2017 15:47

Test API with HttpClient

Nuget

  • Install-Package System.Net.Http
  • Install-Package Newtonsoft.Json
  • Install-Package Microsoft.AspNet.WebApi.Client
  • Install-Package System.Xml.XmlSerializer
  • Install-Package System.Runtime.Serialization.Xml

Guideline

Typed Extensions for HttpClient on .NET Core

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ConsoleApp
{
internal class Program
{
private static void Main(string[] args)
{
DoSomething();
Console.ReadKey();

//var enterResult = "";
//while (enterResult != "Exit")
//{
// Console.WriteLine("Choose an action: ");
// Console.WriteLine("1. LogIn");
// Console.WriteLine("2. Exit");
// switch (Console.ReadLine())
// {
// case "1":
// DoSomething();
// break;

// case "2":
// enterResult = "Exit";
// break;

// default:
// break;
// }
//}
}

private static void DoSomething()
{
const string userName = "projectadmin@gmail.com"; //projectadmin@gmail.com
const string password = "Abc@123";
const string apiBaseAuthUri = "http://192.168.2.26:5000";

//const string apiBaseUri = "http://192.168.2.26:8889/Service";
const string apiBaseUri = "http://localhost:9999";

//const string apiProjectsGetdata = "/api/Projects/GetData";
//const string apiProjectsCloseProject = "/api/Projects/CloseProject/9A75D055-5B34-4132-8EAF-40E1EF4B7C15";
//const string apiDefectsGet = "/api/Defects/9abf6629-b5a1-4a61-8358-a65296fdda29";
//const string apiProjectsUploadFile = "/api/Projects/UploadFile/16fdeeb4-86ca-45f0-ab45-76a18b587b7c";
const string apiProjectsCloseProject = "/api/Projects/CloseProject";
//const string apiProjectsArchiveProject = "/api/Projects/ArchiveProject/de3b7255-92ff-4dee-8f21-0806913e7806";
//const string apiProjectsDeleteProject = "/api/Projects/DeleteProject/67AD6BF5-761B-42F4-8B59-1D9017E966F1";

//const string apiProjectsGetArchived = "/api/Projects/GetArchived?page=1&pagesize=10&searchString=&orderBy=Name&ascending=true";
//const string apiProjectsAll = "/api/Projects/All?page=1&pagesize=10&searchString=&orderBy=Name&ascending=true";

//Get the token
var token = GetApiToken(userName, password, apiBaseAuthUri).Result;
Console.WriteLine("Token: {0}", token);

var closeProjectModel = new CloseProjectModel
{
CloseProjectIds = new List<Guid>
{
Guid.Parse("67AD6BF5-761B-42F4-8B59-1D9017E966F1")
}
};

//Make the HTTP POST
var response = PostRequest(token, apiBaseUri, apiProjectsCloseProject, closeProjectModel).Result;

//Make the HTTP POST
//var response = PostRequest(token, apiBaseUri, apiProjectsArchiveProject).Result;

//Make the HTTP GET
//var response = GetRequest(token, apiBaseUri, apiDefectsGet).Result;

//Make the HTTP DELETE
//var response = DeleteRequest(token, apiBaseUri, apiProjectsDeleteProject).Result;

//Make the HTTP GET All
//var response = GetAll(apiBaseUri, apiProjectsGetArchived).Result;
//var response = GetAll(apiBaseUri, apiProjectsAll).Result;

Console.WriteLine("response: {0}", response);
}

#region Annonymous

public static async Task<string> GetAll(string apiBaseUri, string requestPath)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(apiBaseUri + requestPath);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}

#endregion Annonymous

#region Authentication

private static async Task<string> GetApiToken(string userName, string password, string apiBaseUri)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//setup login data
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", "ro.client"),
new KeyValuePair<string, string>("client_secret", "secret"),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", userName),
new KeyValuePair<string, string>("password", password),
});

//send request
HttpResponseMessage responseMessage = await client.PostAsync("/connect/token", formContent);

//get access token from response body
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseJson);
return jObject.GetValue("access_token").ToString();
}
}


public static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

//make request
HttpResponseMessage response = await client.GetAsync(requestPath);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}

public static async Task<string> PostRequest(string token, string apiBaseUri, string requestPath, object content)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

var myContent = JsonConvert.SerializeObject(content);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.PostAsync(requestPath, byteContent);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}

public static async Task<string> PostRequest(string token, string apiBaseUri, string requestPath)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

var data = new CloseProjectModel
{
CloseProjectIds = new List<Guid>
{
Guid.Parse("67AD6BF5-761B-42F4-8B59-1D9017E966F1")
}
};

var myContent = JsonConvert.SerializeObject(data);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.PostAsync(requestPath, byteContent);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}

public static async Task<string> DeleteRequest(string token, string apiBaseUri, string requestPath)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

HttpResponseMessage response = await client.DeleteAsync(requestPath);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}

#endregion Authentication
}

public class CloseProjectModel
{
public List<Guid> CloseProjectIds { get; set; }

public CloseProjectModel()
{
CloseProjectIds = new List<Guid>();
}
}
}

Categories

Recent posts