public class RestClient
{
public static async Task<T> CallServiceAsync<T>(string token, string endPoint, string url, object requestBodyObject, string method, string operation = null) where T : class
{
if (token == null)
throw new Exception("Please provide token");
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(endPoint + url);
webReq.Method = method;
webReq.Accept = "application/json";
//Add basic authentication header if username is supplied
if (!string.IsNullOrEmpty(token))
webReq.Headers["Authorization"] = "Bearer " + token;
webReq.Headers["Content-Type"] = "application/json";
//Add key to header if operation is supplied
if (!string.IsNullOrEmpty(operation))
webReq.Headers["Operation"] = operation;
//Serialize request object as JSON and write to request body
if (requestBodyObject != null)
{
var requestBody = JsonConvert.SerializeObject(requestBodyObject);
webReq.ContentLength = requestBody.Length;
var streamWriter = new StreamWriter(webReq.GetRequestStream(), Encoding.ASCII);
streamWriter.Write(requestBody);
streamWriter.Close();
}
var response = await webReq.GetResponseAsync();
if (response == null)
{
return default;
}
var streamReader = new StreamReader(response.GetResponseStream());
var responseContent = streamReader.ReadToEnd().Trim();
var jsonObject = JsonConvert.DeserializeObject<T>(responseContent);
return jsonObject;
}
}
Comments
Post a Comment