From 913b4a5f10c4dbbb62932d312e35c28839e721c5 Mon Sep 17 00:00:00 2001 From: runebaas Date: Tue, 28 Jul 2020 22:14:22 +0200 Subject: [PATCH] Change the HttpAbstractions so that the caller can provide its own HttpClient instead of creating parameters for every HttpClient Option --- .../Commands/Utils/Changelog/Changelog.cs | 8 +--- Geekbot.net/Lib/HttpAbstractions.cs | 39 ++++++++++--------- 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs index 335ee3f..c217619 100644 --- a/Geekbot.net/Commands/Utils/Changelog/Changelog.cs +++ b/Geekbot.net/Commands/Utils/Changelog/Changelog.cs @@ -28,13 +28,7 @@ namespace Geekbot.net.Commands.Utils.Changelog { try { - var commits = await HttpAbstractions.Get>( - new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits"), - new Dictionary() - { - { "User-Agent", "http://developer.github.com/v3/#user-agent-required" } - } - ); + var commits = await HttpAbstractions.Get>(new Uri("https://api.github.com/repos/pizzaandcoffee/geekbot.net/commits")); var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 165, 102)); diff --git a/Geekbot.net/Lib/HttpAbstractions.cs b/Geekbot.net/Lib/HttpAbstractions.cs index cf609f6..2cde4cc 100644 --- a/Geekbot.net/Lib/HttpAbstractions.cs +++ b/Geekbot.net/Lib/HttpAbstractions.cs @@ -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 Get(Uri location, Dictionary 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) - { - foreach (var (name, val) in additionalHeaders) - { - client.DefaultRequestHeaders.TryAddWithoutValidation(name, val); - } - } - - var response = await client.GetAsync(location.PathAndQuery); + return client; + } + + public static async Task Get(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) + { + httpClient.Dispose(); + } + return JsonConvert.DeserializeObject(stringResponse); } }