Created
February 19, 2020 15:52
-
-
Save twish/4cf889691da49454b2cc94aea9b46858 to your computer and use it in GitHub Desktop.
Simple wrapper for HttpClient to do REST requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json; | |
namespace Helpers.Web | |
{ | |
public class RestClient | |
{ | |
private static readonly HttpClient Client; | |
/// <summary> | |
/// Create a static configured version of HttpClient, we do not want to implement using statements | |
/// because of how HttpClient behaves. Read: https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests. | |
/// Also we cannot use HttpClientFactory since we are not .net standard. | |
/// </summary> | |
static RestClient() | |
{ | |
Client = new HttpClient(); | |
Client.DefaultRequestHeaders.Accept.Clear(); | |
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
Client.DefaultRequestHeaders.Add("X-AppSecretToken", Settings.GetAppSecretToken); | |
Client.DefaultRequestHeaders.Add("X-AgreementGrantToken", Settings.GetAgreementGrantToken); | |
} | |
public static Task<HttpResponseMessage> GetAsync(string url) | |
{ | |
return Client.GetAsync(url); | |
} | |
public static Task<HttpResponseMessage> PostAsync(string url, HttpContent content) | |
{ | |
return Client.PostAsync(url, content); | |
} | |
public static T DeserializeJsonFromStream<T>(Stream stream) | |
{ | |
if (stream == null || stream.CanRead == false) | |
return default(T); | |
using (var sr = new StreamReader(stream)) | |
using (var jtr = new JsonTextReader(sr)) | |
{ | |
var serializer = new JsonSerializer(); | |
var result = serializer.Deserialize<T>(jtr); | |
return result; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment