36 lines
1.3 KiB
C#
36 lines
1.3 KiB
C#
using System;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Net.Http;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Jellyfin.Plugin.MediaCleaner.Helpers;
|
|
|
|
public static class HttpHelper
|
|
{
|
|
/// <summary>
|
|
/// Sends a JSON request and returns the raw JSON element response.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Do NOT create a new HttpClient on every call; reuse one instance (DI or a singleton) to avoid socket exhaustion.
|
|
/// </remarks>
|
|
public static async Task<JsonElement> SendHttpRequestAsync(HttpClient httpClient, string baseAddress, HttpMethod method, string path, object? body = null)
|
|
{
|
|
var uri = new UriBuilder($"{baseAddress}{path}").Uri;
|
|
using var request = new HttpRequestMessage(method, uri);
|
|
|
|
if (body != null)
|
|
{
|
|
var json = JsonSerializer.Serialize(body);
|
|
request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
|
|
}
|
|
|
|
var response = await httpClient.SendAsync(request).ConfigureAwait(false);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
|
return JsonSerializer.Deserialize<JsonElement>(responseBody);
|
|
}
|
|
}
|