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
|
|
|
|
{
|
2020-07-28 22:14:22 +02:00
|
|
|
public static class HttpAbstractions
|
2020-07-15 02:52:13 +02:00
|
|
|
{
|
2020-07-28 22:14:22 +02:00
|
|
|
public static HttpClient CreateDefaultClient()
|
2020-07-15 02:52:13 +02:00
|
|
|
{
|
2020-07-28 22:14:22 +02:00
|
|
|
var client = new HttpClient
|
2020-07-15 02:52:13 +02:00
|
|
|
{
|
|
|
|
DefaultRequestHeaders =
|
|
|
|
{
|
2020-07-28 22:14:22 +02:00
|
|
|
Accept = {MediaTypeWithQualityHeaderValue.Parse("application/json")},
|
2020-07-15 02:52:13 +02:00
|
|
|
}
|
|
|
|
};
|
2020-07-28 22:14:22 +02:00
|
|
|
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Geekbot/v0.0.0 (+https://geekbot.pizzaandcoffee.rocks/)");
|
2020-07-15 02:52:13 +02:00
|
|
|
|
2020-07-28 22:14:22 +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();
|
2020-07-28 22:14:22 +02:00
|
|
|
|
|
|
|
if (disposeClient)
|
|
|
|
{
|
|
|
|
httpClient.Dispose();
|
|
|
|
}
|
|
|
|
|
2020-07-15 02:52:13 +02:00
|
|
|
return JsonConvert.DeserializeObject<T>(stringResponse);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|