-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHttpClient.cs
704 lines (541 loc) · 21.1 KB
/
HttpClient.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Fody;
using Newtonsoft.Json.Linq;
using Yove.Http.Events;
using Yove.Http.Exceptions;
using Yove.Http.Models;
using Yove.Http.Proxy;
namespace Yove.Http;
[ConfigureAwait(false)]
public class HttpClient : IDisposable
{
#region Public
public NameValueCollection Headers = [];
public NameValueCollection TempHeaders = [];
public NameValueCollection Cookies { get; set; }
public string BaseUrl { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Language { get; set; } = "en-US,en;q=0.9";
public string Referer { get; set; }
public string UserAgent { get; set; }
public string Authorization { get; set; }
public string Accept { get; set; } = "*/*";
public Encoding CharacterSet { get; set; }
public bool KeepAlive { get; set; }
public bool EnableEncodingContent { get; set; } = true;
public bool EnableAutoRedirect { get; set; } = true;
public bool RedirectOnlyIfOtherDomain { get; set; }
public bool EnableProtocolError { get; set; } = true;
public bool EnableCookies { get; set; } = true;
public bool EnableReconnect { get; set; } = true;
public bool HasConnection { get; set; }
public bool IsDisposed { get; set; }
public int KeepAliveTimeOut { get; set; } = 60000;
public int KeepAliveMaxRequest { get; set; } = 100;
public int RedirectLimit { get; set; } = 3;
public int ReconnectLimit { get; set; } = 3;
public int ReconnectDelay { get; set; } = 1000;
public int TimeOut { get; set; } = 60000;
public int ReadWriteTimeOut { get; set; } = 60000;
public long MaxReciveBufferSize { get; set; } = 3147483647;
public Uri Address { get; private set; }
public CancellationToken CancellationToken { get; set; }
public SslProtocols DefaultSslProtocols { get; set; } = SslProtocols.None;
public EventHandler<UploadEvent> UploadProgressChanged { get; set; }
public EventHandler<DownloadEvent> DownloadProgressChanged { get; set; }
public string this[string key]
{
get
{
if (string.IsNullOrEmpty(key))
throw new NullReferenceException("Key is null or empty.");
return Headers[key];
}
set
{
if (!string.IsNullOrEmpty(value))
Headers[key] = value;
}
}
public ProxyClient Proxy
{
get
{
return _proxyClient;
}
set
{
if (_proxyClient != null && HasConnection)
Close();
_proxyClient = value;
}
}
#endregion
#region Private & Internal
internal TcpClient Connection { get; set; }
internal NetworkStream NetworkStream { get; set; }
internal Stream CommonStream { get; set; }
internal HttpMethod Method { get; set; }
internal HttpContent Content { get; set; }
internal List<RedirectItem> RedirectHistory = [];
internal RemoteCertificateValidationCallback AcceptAllCertificationsCallback = new(AcceptAllCertifications);
private HttpResponse _response { get; set; }
private ProxyClient _proxyClient { get; set; }
private int _reconnectCount { get; set; }
private int _keepAliveRequestCount { get; set; }
private int _redirectCount { get; set; }
private DateTime _whenConnectionIdle { get; set; }
private long _sentBytes { get; set; }
private long _receivedBytes { get; set; }
private bool _isReceivedHeader { get; set; }
private long _headerLength { get; set; }
private bool _canReconnect
{
get
{
return EnableReconnect && _reconnectCount < ReconnectLimit;
}
}
private CancellationTokenRegistration _cancellationTokenRegistration { get; set; }
#endregion
public HttpClient()
{
if (EnableCookies && Cookies == null)
Cookies = [];
}
public HttpClient(CancellationToken token) : this()
{
if (token == default)
throw new NullReferenceException("Token cannot be null");
CancellationToken = token;
}
public HttpClient(string baseUrl)
{
BaseUrl = baseUrl;
if (EnableCookies && Cookies == null)
Cookies = [];
}
public HttpClient(string baseUrl, CancellationToken token) : this(baseUrl)
{
if (token == default)
throw new NullReferenceException("Token cannot be null");
CancellationToken = token;
}
public async Task<HttpResponse> Post(string url)
{
return await Raw(HttpMethod.POST, url);
}
public async Task<HttpResponse> Post(string url, string body, string contentType = "application/json")
{
return await Raw(HttpMethod.POST, url, new StringContent(body)
{
ContentType = contentType
});
}
public async Task<HttpResponse> Post(string url, byte[] body, string contentType = "application/octet-stream")
{
return await Raw(HttpMethod.POST, url, new ByteContent(body)
{
ContentType = contentType
});
}
public async Task<HttpResponse> Post(string url, Stream body, string contentType = "application/octet-stream")
{
return await Raw(HttpMethod.POST, url, new StreamContent(body)
{
ContentType = contentType
});
}
public async Task<HttpResponse> Post(string url, HttpContent body)
{
return await Raw(HttpMethod.POST, url, body);
}
public async Task<HttpResponse> Get(string url)
{
return await Raw(HttpMethod.GET, url);
}
public async Task<string> GetString(string url)
{
HttpResponse response = await Raw(HttpMethod.GET, url);
return await response?.Content?.ReadAsString();
}
public async Task<JToken> GetJson(string url)
{
HttpResponse response = await Raw(HttpMethod.GET, url);
return await response?.Content?.ReadAsJson();
}
public async Task<T> GetJson<T>(string url)
{
HttpResponse response = await Raw(HttpMethod.GET, url);
return await response?.Content?.ReadAsJson<T>();
}
public async Task<byte[]> GetBytes(string url)
{
HttpResponse response = await Raw(HttpMethod.GET, url);
return await response?.Content?.ReadAsBytes();
}
public async Task<Stream> GetStream(string url)
{
HttpResponse response = await Raw(HttpMethod.GET, url);
return await response?.Content?.ReadAsStream();
}
public async Task<HttpResponse> Raw(HttpMethod method, string url, HttpContent body = null)
{
if (IsDisposed)
throw new ObjectDisposedException("Object disposed.");
if (string.IsNullOrEmpty(url))
throw new NullReferenceException("URL is null or empty.");
if (CancellationToken != default)
{
if (_cancellationTokenRegistration != default)
_cancellationTokenRegistration.Dispose();
CancellationToken.ThrowIfCancellationRequested();
_cancellationTokenRegistration = CancellationToken.Register(() =>
{
_reconnectCount = ReconnectLimit;
Close();
});
}
if (!url.StartsWith("https://") && !url.StartsWith("http://") && !string.IsNullOrEmpty(BaseUrl))
url = $"{BaseUrl.TrimEnd('/')}/{url}";
if (!EnableCookies && Cookies != null)
Cookies = null;
Method = method;
Content = body;
_receivedBytes = 0;
_sentBytes = 0;
TimeSpan timeResponseStart = DateTime.Now.TimeOfDay;
if (CheckKeepAlive() || Address.Host != new UriBuilder(url).Host)
{
Close();
Address = new UriBuilder(url).Uri;
try
{
Connection = await CreateConnection(Address.Host, Address.Port);
NetworkStream = Connection.GetStream();
if (Address.Scheme.StartsWith("https"))
{
SslStream sslStream = new(NetworkStream, false, AcceptAllCertificationsCallback);
await sslStream.AuthenticateAsClientAsync(Address.Host, null, DefaultSslProtocols, false);
CommonStream = sslStream;
}
else
{
CommonStream = NetworkStream;
}
HasConnection = true;
if (DownloadProgressChanged != null || UploadProgressChanged != null)
{
EventStreamWrapper eventStream = new(CommonStream, Connection.SendBufferSize);
if (UploadProgressChanged != null)
{
eventStream.WriteBytesCallback = (e) =>
{
_sentBytes += e;
if (Content?.ContentLength != null)
{
UploadProgressChanged?.Invoke(this,
new UploadEvent(_sentBytes - _headerLength, Content.ContentLength));
}
};
}
if (DownloadProgressChanged != null)
{
eventStream.ReadBytesCallback = (e) =>
{
_receivedBytes += e;
if (_isReceivedHeader && _response?.ContentLength != null)
{
DownloadProgressChanged?.Invoke(this,
new DownloadEvent(_receivedBytes - _response.HeaderLength, _response.ContentLength));
}
};
}
CommonStream = eventStream;
}
}
catch (Exception ex)
{
if (ex?.InnerException?.Message == "bad protocol version")
#pragma warning disable SYSLIB0039 // Type or member is obsolete
DefaultSslProtocols = SslProtocols.Tls11;
#pragma warning restore SYSLIB0039 // Type or member is obsolete
if (_canReconnect)
return await Reconnect(method, url, body);
throw new HttpRequestException($"Failed Connection to Address: {Address.AbsoluteUri}", ex);
}
}
else
{
Address = new UriBuilder(url).Uri;
}
try
{
long contentLength = 0L;
string contentType = null;
if (Method != HttpMethod.GET && Content != null)
{
contentType = Content.ContentType;
contentLength = Content.ContentLength;
}
string stringHeader = $"{Method} {Address.PathAndQuery} HTTP/1.1\r\n{GenerateHeaders(Method, contentLength, contentType)}";
byte[] headersBytes = Encoding.ASCII.GetBytes(stringHeader);
_headerLength = headersBytes.Length;
CommonStream.Write(headersBytes, 0, headersBytes.Length);
if (Content != null && contentLength != 0)
Content.Write(CommonStream);
}
catch (Exception ex)
{
if (_canReconnect)
return await Reconnect(method, url, body);
throw new HttpRequestException($"Failed send data to Address: {Address.AbsoluteUri}", ex);
}
try
{
_isReceivedHeader = false;
_response?.Content?.Dispose();
_response = new HttpResponse(this);
_isReceivedHeader = true;
}
catch (Exception ex)
{
if (_canReconnect)
return await Reconnect(method, url, body);
throw new HttpResponseException($"Failed receive data from Address: {Address.AbsoluteUri}", ex);
}
_reconnectCount = 0;
_whenConnectionIdle = DateTime.Now;
_response.TimeResponse = (DateTime.Now - timeResponseStart).TimeOfDay;
if (EnableProtocolError)
{
if ((int)_response.StatusCode >= 400 && (int)_response.StatusCode < 500)
throw new HttpResponseException($"[Client] | Status Code - {_response.StatusCode}");
else if ((int)_response.StatusCode >= 500)
throw new HttpResponseException($"[Server] | Status Code - {_response.StatusCode}");
}
if (EnableAutoRedirect && _response.Location != null && _redirectCount < RedirectLimit &&
((_response.RedirectAddress.Host == Address.Host && _response.RedirectAddress.Scheme != Address.Scheme) ||
!RedirectOnlyIfOtherDomain || (RedirectOnlyIfOtherDomain && _response.RedirectAddress.Host != Address.Host)))
{
_redirectCount++;
string location = _response.Location;
RedirectHistory.Add(new RedirectItem
{
From = url,
To = location,
StatusCode = (int)_response.StatusCode,
Length = _response.ContentLength,
ContentType = _response.ContentType
});
Close();
return await Raw(HttpMethod.GET, location, null);
}
_redirectCount = 0;
RedirectHistory.Clear();
return _response;
}
private bool CheckKeepAlive()
{
int maxRequest = (_response != null && _response.KeepAliveMax != 0) ? _response.KeepAliveMax : KeepAliveMaxRequest;
return _keepAliveRequestCount == 0 || _keepAliveRequestCount == maxRequest ||
_response?.ConnectionClose == true || !HasConnection ||
_whenConnectionIdle.AddMilliseconds(TimeOut) < DateTime.Now;
}
private async Task<TcpClient> CreateConnection(string host, int port)
{
if (Proxy == null)
{
TcpClient tcpClient = new()
{
ReceiveTimeout = ReadWriteTimeOut,
SendTimeout = ReadWriteTimeOut
};
using CancellationTokenSource cancellationToken = new(TimeSpan.FromMilliseconds(TimeOut));
try
{
#if NETSTANDARD2_1 || NETCOREAPP3_1
tcpClient.ConnectAsync(host, port).Wait(cancellationToken.Token);
#elif NET5_0_OR_GREATER
await tcpClient.ConnectAsync(host, port, cancellationToken.Token);
#endif
if (!tcpClient.Connected)
throw new();
}
catch
{
tcpClient.Dispose();
throw new HttpRequestException($"Failed Connection to Address: {Address.AbsoluteUri}");
}
return tcpClient;
}
else
{
return await Proxy.CreateConnection(host, port);
}
}
private string GenerateHeaders(HttpMethod method, long contentLength = 0, string contentType = null)
{
NameValueCollection rawHeaders = [];
if (Address.IsDefaultPort)
rawHeaders["Host"] = Address.Host;
else
rawHeaders["Host"] = $"{Address.Host}:{Address.Port}";
if (!string.IsNullOrEmpty(UserAgent))
rawHeaders["User-Agent"] = UserAgent;
if (!Headers.AllKeys.Contains("Accept"))
rawHeaders["Accept"] = Accept;
if (!Headers.AllKeys.Contains("Accept-Language"))
rawHeaders["Accept-Language"] = Language;
if (EnableEncodingContent)
rawHeaders["Accept-Encoding"] = "deflate, gzip, br";
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
rawHeaders["Authorization"] = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))}";
if (!string.IsNullOrEmpty(Referer))
rawHeaders["Referer"] = Referer;
if (!string.IsNullOrEmpty(Authorization))
rawHeaders["Authorization"] = Authorization;
if (CharacterSet != null)
{
if (CharacterSet != Encoding.UTF8)
rawHeaders["Accept-Charset"] = $"{CharacterSet.WebName},utf-8";
else
rawHeaders["Accept-Charset"] = "utf-8";
}
if (method != HttpMethod.GET)
{
if (contentLength > 0)
rawHeaders["Content-Type"] = contentType;
rawHeaders["Content-Length"] = contentLength.ToString();
}
if (Proxy?.Type == ProxyType.Http)
{
if (KeepAlive)
{
rawHeaders["Proxy-Connection"] = "keep-alive";
_keepAliveRequestCount++;
}
else
{
rawHeaders["Proxy-Connection"] = "close";
}
}
else if (KeepAlive)
{
rawHeaders["Connection"] = "keep-alive";
_keepAliveRequestCount++;
}
else
{
rawHeaders["Connection"] = "close";
}
if (Cookies?.Count > 0)
{
string cookieBuilder = string.Empty;
foreach (string cookie in Cookies)
cookieBuilder += $"{cookie}={Cookies[cookie]}; ";
rawHeaders["Cookie"] = cookieBuilder.TrimEnd();
}
StringBuilder headerBuilder = new();
foreach (string header in rawHeaders)
headerBuilder.Append($"{header}: {rawHeaders[header]}\r\n");
foreach (string header in Headers)
headerBuilder.Append($"{header}: {Headers[header]}\r\n");
foreach (string header in TempHeaders)
headerBuilder.Append($"{header}: {TempHeaders[header]}\r\n");
TempHeaders.Clear();
return $"{headerBuilder}\r\n";
}
public void AddTempHeader(string key, string value)
{
if (string.IsNullOrEmpty(key))
throw new NullReferenceException("Key is null or empty.");
if (string.IsNullOrEmpty(value))
throw new NullReferenceException("Value is null or empty.");
TempHeaders.Add(key, value);
}
public void AddRawCookie(string source)
{
if (string.IsNullOrEmpty(source))
throw new NullReferenceException("Value is null or empty.");
if (!EnableCookies)
throw new HttpRequestException("Cookies is disabled.");
if (source.Contains("Cookie:", StringComparison.OrdinalIgnoreCase))
source = source.Replace("Cookie:", "", StringComparison.OrdinalIgnoreCase).Trim();
foreach (string cookie in source.Split(';'))
{
string key = cookie.Split('=')[0]?.Trim();
string value = cookie.Split('=')[1]?.Trim();
if (key != null && value != null)
Cookies[key] = value;
}
}
private async Task<HttpResponse> Reconnect(HttpMethod method, string url, HttpContent body = null)
{
Close();
_reconnectCount++;
await Task.Delay(ReconnectDelay);
return await Raw(method, url, body);
}
private static bool AcceptAllCertifications(object sender, X509Certificate certification, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public void Close()
{
Connection?.Close();
Connection?.Dispose();
Connection = null;
NetworkStream?.Close();
NetworkStream?.Dispose();
NetworkStream = null;
CommonStream?.Close();
CommonStream?.Dispose();
CommonStream = null;
_keepAliveRequestCount = 0;
HasConnection = false;
}
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
Content?.Dispose();
_response?.Content?.Dispose();
if (_cancellationTokenRegistration != default)
_cancellationTokenRegistration.Dispose();
}
Close();
_response = null;
_proxyClient = null;
Cookies = null;
Headers = null;
TempHeaders = null;
RedirectHistory = null;
Content = null;
IsDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~HttpClient()
{
Dispose(false);
}
}