Change the HttpAbstractions so that the caller can provide its own HttpClient instead of creating parameters for every HttpClient Option

This commit is contained in:
runebaas 2020-07-28 22:14:22 +02:00
parent 4659f793f5
commit 913b4a5f10
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
2 changed files with 21 additions and 26 deletions

View file

@ -28,13 +28,7 @@ namespace Geekbot.net.Commands.Utils.Changelog
{
try
{
var commits = await HttpAbstractions.Get<List<CommitDto>>(
new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits"),
new Dictionary<string, string>()
{
{ "User-Agent", "http://developer.github.com/v3/#user-agent-required" }
}
);
var commits = await HttpAbstractions.Get<List<CommitDto>>(new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits"));
var eb = new EmbedBuilder();
eb.WithColor(new Color(143, 165, 102));

View file

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
@ -7,34 +6,36 @@ using Newtonsoft.Json;
namespace Geekbot.net.Lib
{
public class HttpAbstractions
public static class HttpAbstractions
{
public static async Task<T> Get<T>(Uri location, Dictionary<string, string> additionalHeaders = null)
public static HttpClient CreateDefaultClient()
{
using var client = new HttpClient
var client = new HttpClient
{
BaseAddress = location,
DefaultRequestHeaders =
{
Accept =
{
MediaTypeWithQualityHeaderValue.Parse("application/json")
}
Accept = {MediaTypeWithQualityHeaderValue.Parse("application/json")},
}
};
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Geekbot/v0.0.0 (+https://geekbot.pizzaandcoffee.rocks/)");
if (additionalHeaders != null)
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);
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
if (disposeClient)
{
foreach (var (name, val) in additionalHeaders)
{
client.DefaultRequestHeaders.TryAddWithoutValidation(name, val);
}
httpClient.Dispose();
}
var response = await client.GetAsync(location.PathAndQuery);
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(stringResponse);
}
}