geekbot/Geekbot.net/Lib/HttpAbstractions.cs

42 lines
1.3 KiB
C#
Raw Normal View History

2020-07-15 02:52:13 +02:00
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Geekbot.net.Lib
{
public static class HttpAbstractions
2020-07-15 02:52:13 +02:00
{
public static HttpClient CreateDefaultClient()
2020-07-15 02:52:13 +02:00
{
var client = new HttpClient
2020-07-15 02:52:13 +02:00
{
DefaultRequestHeaders =
{
Accept = {MediaTypeWithQualityHeaderValue.Parse("application/json")},
2020-07-15 02:52:13 +02:00
}
};
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Geekbot/v0.0.0 (+https://geekbot.pizzaandcoffee.rocks/)");
2020-07-15 02:52:13 +02:00
return client;
}
public static async Task<T> Get<T>(Uri location, HttpClient httpClient = null, bool disposeClient = true)
{
httpClient ??= CreateDefaultClient();
httpClient.BaseAddress = location;
var response = await httpClient.GetAsync(location.PathAndQuery);
2020-07-15 02:52:13 +02:00
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
if (disposeClient)
{
httpClient.Dispose();
}
2020-07-15 02:52:13 +02:00
return JsonConvert.DeserializeObject<T>(stringResponse);
}
}
}