Skip to content

Commit

Permalink
优化 HttpClient
Browse files Browse the repository at this point in the history
  • Loading branch information
reitowo committed Nov 25, 2023
1 parent 6778d93 commit 3c9e062
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions Api/Base/ApiBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ public class ApiBase {

private HttpContent _content;

private static HttpClient _client;

static ApiBase() {
_client = new HttpClient(new SocketsHttpHandler() {
PooledConnectionLifetime = TimeSpan.FromMinutes(30)
});
_client.Timeout = TimeSpan.FromSeconds(10);
}

public ApiBase(OpenApiAccessInfo openApiAccessInfo) {
_openApiAccessInfo = openApiAccessInfo;
_openApiAccessInfo.Validate();
Expand Down Expand Up @@ -115,15 +124,13 @@ public async Task<JToken> RequestAsync(string api, HttpMethod method) {
_requestUrl = $"{_requestUrl}?{_queryParam}";
}

using var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(10);
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"QQBot {await _openApiAccessInfo.GetAuthorization()}");
client.DefaultRequestHeaders.TryAddWithoutValidation("X-Union-Appid", _openApiAccessInfo.BotAppId);

var req = new HttpRequestMessage(method, _requestUrl);
req.Headers.TryAddWithoutValidation("Authorization", $"QQBot {await _openApiAccessInfo.GetAuthorization()}");
req.Headers.TryAddWithoutValidation("X-Union-Appid", _openApiAccessInfo.BotAppId);

if (req.Method != HttpMethod.Get)
req.Content = _content;
responseMessage = await client.SendAsync(req).ConfigureAwait(false);
responseMessage = await _client.SendAsync(req).ConfigureAwait(false);

var traceId = "Missing";
if (responseMessage.Headers.TryGetValues("X-Tps-Trace-Id", out var val)) {
Expand Down

0 comments on commit 3c9e062

Please sign in to comment.