-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseHTTPClient.cs
101 lines (78 loc) · 2.93 KB
/
BaseHTTPClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
namespace TAC_Grabber
{
public abstract class BaseHTTPClient
{
protected readonly HttpMessageInvoker client;
AsyncPolicyWrap<HttpResponseMessage> policyWrap;
HttpStatusCode[] excludeStatusCode= new[]
{
HttpStatusCode.NotFound,
HttpStatusCode.BadRequest
};
public BaseHTTPClient(HttpMessageInvoker httpClient)
{
if (httpClient == null)
throw new ArgumentNullException(nameof(httpClient));
client = httpClient;
var retryPolicy = Policy
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.OrResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode && !excludeStatusCode.Contains(r.StatusCode))
.WaitAndRetryForeverAsync(retryAttemp => TimeSpan.FromSeconds(Math.Pow(2, retryAttemp)));
var reauthPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.RetryAsync(
retryCount: 1,
onRetryAsync: (outcome, retryNumber, context) => ReAuthAsync()
);
policyWrap = Policy.WrapAsync<HttpResponseMessage>(retryPolicy, reauthPolicy);
}
public async Task<string> GetQueryAsync(string query)
{
var response = await QueryAsync(query);
return await ProcessResponseAsync(response);
}
private static JsonSerializerOptions serializerOptions = new JsonSerializerOptions
{
IgnoreNullValues = true,
PropertyNameCaseInsensitive = true,
AllowTrailingCommas = true,
};
protected async Task<T> Deserialize<T>(HttpResponseMessage responseMessage)
{
T value = default;
if (responseMessage.IsSuccessStatusCode)
{
var stream = await responseMessage.Content.ReadAsStreamAsync();
try
{
value = await JsonSerializer.DeserializeAsync<T>(stream, serializerOptions);
}
catch { }
}
return value;
}
protected Task<HttpResponseMessage> QueryAsync(string query)
{
return policyWrap.ExecuteAsync(() =>
{
var message = GetRequestMessage(query);
return client.SendAsync(message, default);
});
}
protected virtual Task ReAuthAsync()
{
return Task.CompletedTask;
}
protected abstract HttpRequestMessage GetRequestMessage(string query);
protected abstract Task<string> ProcessResponseAsync(HttpResponseMessage response);
}
}