This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
beatsaber-scoretracker/Mod/API/Request.cs

53 lines
1.9 KiB
C#
Raw Normal View History

2024-08-07 05:19:39 +01:00
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ScoreTracker.API
{
internal class Request
{
2024-08-07 08:26:12 +01:00
internal static readonly HttpClient HttpClient = new HttpClient();
2024-08-07 05:19:39 +01:00
/// <summary>
/// Persist the given headers for all future requests
/// </summary>
/// <param name="headers">the headers to persist</param>
public static void PersistHeaders(Dictionary<string, string> headers)
{
2024-08-07 08:26:12 +01:00
HttpClient.DefaultRequestHeaders.Clear(); // Clear existing headers
2024-08-07 05:19:39 +01:00
foreach (var header in headers)
{
2024-08-07 08:26:12 +01:00
HttpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
2024-08-07 05:19:39 +01:00
}
}
/// <summary>
/// Create a POST request to the given URL with the given data
/// </summary>
/// <param name="url">the url to post to</param>
/// <param name="data">the data to post</param>
/// <param name="checkAuth">whether to check for authentication</param>
/// <returns>the task</returns>
public static async Task<HttpResponseMessage> PostJsonAsync(string url, Dictionary<object, object> json, bool checkAuth = true)
{
if (checkAuth)
{
2024-08-15 18:22:16 +01:00
var signinResponse = await Authentication.ValidateAndSignIn();
if (!signinResponse.Success)
2024-08-07 05:19:39 +01:00
{
2024-08-15 18:22:16 +01:00
throw new Exception($"Failed to log in: {signinResponse.Response}");
2024-08-07 05:19:39 +01:00
}
}
var jsonString = JsonConvert.SerializeObject(json, Formatting.None);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
// Send the POST request
2024-08-07 08:26:12 +01:00
var response = await HttpClient.PostAsync(url, content);
2024-08-07 05:19:39 +01:00
return response;
}
}
}