using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace XFEWarframe.Admin.Implements.Services;
public sealed class ApiClient : IDisposable
{
private readonly HttpClient client = new(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(20) };
public string Address { get; set; } = "http://127.0.0.1:8444";
public string Token { get; set; } = "";
public async Task<JToken> Get(string path, CancellationToken cancellationToken = default) => await Send(HttpMethod.Get, path, null, cancellationToken);
public async Task<JToken> Post(string path, object body, CancellationToken cancellationToken = default) => await Send(HttpMethod.Post, path, body, cancellationToken);
private async Task<JToken> Send(HttpMethod method, string path, object? data, CancellationToken cancellationToken)
{
if (!Uri.TryCreate(Address, UriKind.Absolute, out var origin) || origin.Scheme is not ("http" or "https") || origin.AbsolutePath != "/" || !string.IsNullOrEmpty(origin.UserInfo)) throw new InvalidOperationException("请输入有效的 HTTP(S) 服务器地址");
// ServerInteractive 4.0.1 rejects percent-encoded slashes even in query data.
// A literal slash is legal there; never unescape the route or query separators.
var queryAt = path.IndexOf('?');
if (queryAt >= 0) path = path[..queryAt] + path[queryAt..].Replace("%2F", "/", StringComparison.OrdinalIgnoreCase);
using var request = new HttpRequestMessage(method, Address.TrimEnd('/') + "/control/v1/" + path);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token);
if (data is not null) request.Content = new StringContent(await Task.Run(() => JsonConvert.SerializeObject(data), cancellationToken).ConfigureAwait(false), Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
return await Task.Run<JToken>(() =>
{
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new InvalidOperationException("服务器缺少此接口。请启动同一发行包中的新版 Server,并确认连接地址与端口。");
string message;
try { message = JObject.Parse(text).Value<string>("error") ?? text; } catch (JsonException) { message = text; }
throw new InvalidOperationException($"HTTP {(int)response.StatusCode} · {message}");
}
if (string.IsNullOrWhiteSpace(text)) return new JObject();
using var reader = new JsonTextReader(new StringReader(text)) { DateParseHandling = DateParseHandling.DateTimeOffset };
return JToken.Load(reader);
}, cancellationToken).ConfigureAwait(false);
}
public void Dispose() => client.Dispose();
}
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace XFEWarframe.Admin.Implements.Services;
public sealed class ApiClient : IDisposable
{
private readonly HttpClient client = new(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(20) };
public string Address { get; set; } = "http://127.0.0.1:8444";
public string Token { get; set; } = "";
public async Task<JToken> Get(string path, CancellationToken cancellationToken = default) => await Send(HttpMethod.Get, path, null, cancellationToken);
public async Task<JToken> Post(string path, object body, CancellationToken cancellationToken = default) => await Send(HttpMethod.Post, path, body, cancellationToken);
private async Task<JToken> Send(HttpMethod method, string path, object? data, CancellationToken cancellationToken)
{
if (!Uri.TryCreate(Address, UriKind.Absolute, out var origin) || origin.Scheme is not ("http" or "https") || origin.AbsolutePath != "/" || !string.IsNullOrEmpty(origin.UserInfo)) throw new InvalidOperationException("请输入有效的 HTTP(S) 服务器地址");
// ServerInteractive 4.0.1 rejects percent-encoded slashes even in query data.
// A literal slash is legal there; never unescape the route or query separators.
var queryAt = path.IndexOf('?');
if (queryAt >= 0) path = path[..queryAt] + path[queryAt..].Replace("%2F", "/", StringComparison.OrdinalIgnoreCase);
using var request = new HttpRequestMessage(method, Address.TrimEnd('/') + "/control/v1/" + path);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token);
if (data is not null) request.Content = new StringContent(await Task.Run(() => JsonConvert.SerializeObject(data), cancellationToken).ConfigureAwait(false), Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
return await Task.Run<JToken>(() =>
{
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new InvalidOperationException("服务器缺少此接口。请启动同一发行包中的新版 Server,并确认连接地址与端口。");
string message;
try { message = JObject.Parse(text).Value<string>("error") ?? text; } catch (JsonException) { message = text; }
throw new InvalidOperationException($"HTTP {(int)response.StatusCode} · {message}");
}
if (string.IsNullOrWhiteSpace(text)) return new JObject();
using var reader = new JsonTextReader(new StringReader(text)) { DateParseHandling = DateParseHandling.DateTimeOffset };
return JToken.Load(reader);
}, cancellationToken).ConfigureAwait(false);
}
public void Dispose() => client.Dispose();
}