-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
WebClient.cs
2199 lines (1862 loc) · 83.5 KB
/
WebClient.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net.Cache;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public class WebClient : Component
{
private const int DefaultCopyBufferLength = 8192;
private const int DefaultDownloadBufferLength = 65536;
private const string DefaultUploadFileContentType = "application/octet-stream";
private const string UploadFileContentType = "multipart/form-data";
private const string UploadValuesContentType = "application/x-www-form-urlencoded";
private Uri? _baseAddress;
private ICredentials? _credentials;
private WebHeaderCollection? _headers;
private NameValueCollection? _requestParameters;
private WebResponse? _webResponse;
private WebRequest? _webRequest;
private Encoding _encoding = Encoding.Default;
private string? _method;
private long _contentLength = -1;
private bool _initWebClientAsync;
private bool _canceled;
private ProgressData? _progress;
private IWebProxy? _proxy;
private bool _proxySet;
private int _callNesting; // > 0 if we're in a Read/Write call
private AsyncOperation? _asyncOp;
private SendOrPostCallback? _downloadDataOperationCompleted;
private SendOrPostCallback? _openReadOperationCompleted;
private SendOrPostCallback? _openWriteOperationCompleted;
private SendOrPostCallback? _downloadStringOperationCompleted;
private SendOrPostCallback? _downloadFileOperationCompleted;
private SendOrPostCallback? _uploadStringOperationCompleted;
private SendOrPostCallback? _uploadDataOperationCompleted;
private SendOrPostCallback? _uploadFileOperationCompleted;
private SendOrPostCallback? _uploadValuesOperationCompleted;
private SendOrPostCallback? _reportDownloadProgressChanged;
private SendOrPostCallback? _reportUploadProgressChanged;
[Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public WebClient()
{
// We don't know if derived types need finalizing, but WebClient doesn't.
if (GetType() == typeof(WebClient))
{
GC.SuppressFinalize(this);
}
}
public event DownloadStringCompletedEventHandler? DownloadStringCompleted;
public event DownloadDataCompletedEventHandler? DownloadDataCompleted;
public event AsyncCompletedEventHandler? DownloadFileCompleted;
public event UploadStringCompletedEventHandler? UploadStringCompleted;
public event UploadDataCompletedEventHandler? UploadDataCompleted;
public event UploadFileCompletedEventHandler? UploadFileCompleted;
public event UploadValuesCompletedEventHandler? UploadValuesCompleted;
public event OpenReadCompletedEventHandler? OpenReadCompleted;
public event OpenWriteCompletedEventHandler? OpenWriteCompleted;
public event DownloadProgressChangedEventHandler? DownloadProgressChanged;
public event UploadProgressChangedEventHandler? UploadProgressChanged;
protected virtual void OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) => DownloadStringCompleted?.Invoke(this, e);
protected virtual void OnDownloadDataCompleted(DownloadDataCompletedEventArgs e) => DownloadDataCompleted?.Invoke(this, e);
protected virtual void OnDownloadFileCompleted(AsyncCompletedEventArgs e) => DownloadFileCompleted?.Invoke(this, e);
protected virtual void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e) => DownloadProgressChanged?.Invoke(this, e);
protected virtual void OnUploadStringCompleted(UploadStringCompletedEventArgs e) => UploadStringCompleted?.Invoke(this, e);
protected virtual void OnUploadDataCompleted(UploadDataCompletedEventArgs e) => UploadDataCompleted?.Invoke(this, e);
protected virtual void OnUploadFileCompleted(UploadFileCompletedEventArgs e) => UploadFileCompleted?.Invoke(this, e);
protected virtual void OnUploadValuesCompleted(UploadValuesCompletedEventArgs e) => UploadValuesCompleted?.Invoke(this, e);
protected virtual void OnUploadProgressChanged(UploadProgressChangedEventArgs e) => UploadProgressChanged?.Invoke(this, e);
protected virtual void OnOpenReadCompleted(OpenReadCompletedEventArgs e) => OpenReadCompleted?.Invoke(this, e);
protected virtual void OnOpenWriteCompleted(OpenWriteCompletedEventArgs e) => OpenWriteCompleted?.Invoke(this, e);
private void StartOperation()
{
if (Interlocked.Increment(ref _callNesting) > 1)
{
EndOperation();
throw new NotSupportedException(SR.net_webclient_no_concurrent_io_allowed);
}
_contentLength = -1;
_webResponse = null;
_webRequest = null;
_method = null;
_canceled = false;
_progress?.Reset();
}
private AsyncOperation StartAsyncOperation(object? userToken)
{
if (!_initWebClientAsync)
{
// Set up the async delegates
_openReadOperationCompleted = arg => OnOpenReadCompleted((OpenReadCompletedEventArgs)arg!);
_openWriteOperationCompleted = arg => OnOpenWriteCompleted((OpenWriteCompletedEventArgs)arg!);
_downloadStringOperationCompleted = arg => OnDownloadStringCompleted((DownloadStringCompletedEventArgs)arg!);
_downloadDataOperationCompleted = arg => OnDownloadDataCompleted((DownloadDataCompletedEventArgs)arg!);
_downloadFileOperationCompleted = arg => OnDownloadFileCompleted((AsyncCompletedEventArgs)arg!);
_uploadStringOperationCompleted = arg => OnUploadStringCompleted((UploadStringCompletedEventArgs)arg!);
_uploadDataOperationCompleted = arg => OnUploadDataCompleted((UploadDataCompletedEventArgs)arg!);
_uploadFileOperationCompleted = arg => OnUploadFileCompleted((UploadFileCompletedEventArgs)arg!);
_uploadValuesOperationCompleted = arg => OnUploadValuesCompleted((UploadValuesCompletedEventArgs)arg!);
_reportDownloadProgressChanged = arg => OnDownloadProgressChanged((DownloadProgressChangedEventArgs)arg!);
_reportUploadProgressChanged = arg => OnUploadProgressChanged((UploadProgressChangedEventArgs)arg!);
_progress = new ProgressData();
_initWebClientAsync = true;
}
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userToken);
StartOperation();
_asyncOp = asyncOp;
return asyncOp;
}
private void EndOperation() => Interlocked.Decrement(ref _callNesting);
public Encoding Encoding
{
get { return _encoding; }
set
{
ArgumentNullException.ThrowIfNull(value);
_encoding = value;
}
}
[AllowNull]
public string BaseAddress
{
get { return _baseAddress != null ? _baseAddress.ToString() : string.Empty; }
set
{
if (string.IsNullOrEmpty(value))
{
_baseAddress = null;
}
else
{
try
{
_baseAddress = new Uri(value);
}
catch (UriFormatException e)
{
throw new ArgumentException(SR.net_webclient_invalid_baseaddress, nameof(value), e);
}
}
}
}
public ICredentials? Credentials
{
get { return _credentials; }
set { _credentials = value; }
}
public bool UseDefaultCredentials
{
get { return _credentials == CredentialCache.DefaultCredentials; }
set { _credentials = value ? CredentialCache.DefaultCredentials : null; }
}
[AllowNull]
public WebHeaderCollection Headers
{
get { return _headers ??= new WebHeaderCollection(); }
set { _headers = value; }
}
[AllowNull]
public NameValueCollection QueryString
{
get { return _requestParameters ??= new NameValueCollection(); }
set { _requestParameters = value; }
}
public WebHeaderCollection? ResponseHeaders => _webResponse?.Headers;
public IWebProxy? Proxy
{
get { return _proxySet ? _proxy : WebRequest.DefaultWebProxy; }
set
{
_proxy = value;
_proxySet = true;
}
}
public RequestCachePolicy? CachePolicy { get; set; }
public bool IsBusy => Volatile.Read(ref _callNesting) > 0;
protected virtual WebRequest GetWebRequest(Uri address)
{
#pragma warning disable SYSLIB0014 // WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.
WebRequest request = WebRequest.Create(address);
#pragma warning restore SYSLIB0014
CopyHeadersTo(request);
if (Credentials != null)
{
request.Credentials = Credentials;
}
if (_method != null)
{
request.Method = _method;
}
if (_contentLength != -1)
{
request.ContentLength = _contentLength;
}
if (_proxySet)
{
request.Proxy = _proxy;
}
if (CachePolicy != null)
{
request.CachePolicy = CachePolicy;
}
return request;
}
protected virtual WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = request.GetResponse();
_webResponse = response;
return response;
}
protected virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = request.EndGetResponse(result);
_webResponse = response;
return response;
}
private async Task<WebResponse> GetWebResponseTaskAsync(WebRequest request)
{
// We would like to simply await request.GetResponseAsync(), but WebClient exposes
// a protected member GetWebResponse(WebRequest, IAsyncResult) that derived instances expect to
// be used to get the response, and it needs to be passed the IAsyncResult that was returned
// from WebRequest.BeginGetResponse.
var awaitable = new BeginEndAwaitableAdapter();
request.BeginGetResponse(BeginEndAwaitableAdapter.Callback, awaitable);
return GetWebResponse(request, await awaitable);
}
public byte[] DownloadData(string address) =>
DownloadData(GetUri(address));
public byte[] DownloadData(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
StartOperation();
try
{
WebRequest request;
return DownloadDataInternal(address, out request);
}
finally
{
EndOperation();
}
}
private byte[] DownloadDataInternal(Uri address, out WebRequest request)
{
WebRequest? tmpRequest = null;
byte[] result;
try
{
tmpRequest = _webRequest = GetWebRequest(GetUri(address));
result = DownloadBits(tmpRequest, new ChunkedMemoryStream())!;
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(tmpRequest);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
request = tmpRequest;
return result;
}
public void DownloadFile(string address, string fileName) =>
DownloadFile(GetUri(address), fileName);
public void DownloadFile(Uri address, string fileName)
{
ArgumentNullException.ThrowIfNull(address);
ArgumentNullException.ThrowIfNull(fileName);
WebRequest? request = null;
FileStream? fs = null;
bool succeeded = false;
StartOperation();
try
{
fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
request = _webRequest = GetWebRequest(GetUri(address));
DownloadBits(request, fs);
succeeded = true;
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
finally
{
if (fs != null)
{
fs.Close();
if (!succeeded)
{
File.Delete(fileName);
}
}
EndOperation();
}
}
public Stream OpenRead(string address) =>
OpenRead(GetUri(address));
public Stream OpenRead(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
WebRequest? request = null;
StartOperation();
try
{
request = _webRequest = GetWebRequest(GetUri(address));
WebResponse response = _webResponse = GetWebResponse(request);
return response.GetResponseStream();
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
finally
{
EndOperation();
}
}
public Stream OpenWrite(string address) =>
OpenWrite(GetUri(address), null);
public Stream OpenWrite(Uri address) =>
OpenWrite(address, null);
public Stream OpenWrite(string address, string? method) =>
OpenWrite(GetUri(address), method);
public Stream OpenWrite(Uri address, string? method)
{
ArgumentNullException.ThrowIfNull(address);
method ??= MapToDefaultMethod(address);
WebRequest? request = null;
StartOperation();
try
{
_method = method;
request = _webRequest = GetWebRequest(GetUri(address));
return new WebClientWriteStream(
request.GetRequestStream(),
request,
this);
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
finally
{
EndOperation();
}
}
public byte[] UploadData(string address, byte[] data) =>
UploadData(GetUri(address), null, data);
public byte[] UploadData(Uri address, byte[] data) =>
UploadData(address, null, data);
public byte[] UploadData(string address, string? method, byte[] data) =>
UploadData(GetUri(address), method, data);
public byte[] UploadData(Uri address, string? method, byte[] data)
{
ArgumentNullException.ThrowIfNull(address);
ArgumentNullException.ThrowIfNull(data);
method ??= MapToDefaultMethod(address);
StartOperation();
try
{
WebRequest request;
return UploadDataInternal(address, method, data, out request);
}
finally
{
EndOperation();
}
}
private byte[] UploadDataInternal(Uri address, string method, byte[] data, out WebRequest request)
{
WebRequest? tmpRequest = null;
byte[] result;
try
{
_method = method;
_contentLength = data.Length;
tmpRequest = _webRequest = GetWebRequest(GetUri(address));
result = UploadBits(tmpRequest, null, data, 0, null, null);
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(tmpRequest);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
request = tmpRequest;
return result;
}
private void OpenFileInternal(
bool needsHeaderAndBoundary, string fileName,
out FileStream fs, out byte[] buffer, ref byte[]? formHeaderBytes, ref byte[]? boundaryBytes)
{
fileName = Path.GetFullPath(fileName);
WebHeaderCollection headers = Headers;
string? contentType = headers[HttpKnownHeaderNames.ContentType];
if (contentType == null)
{
contentType = DefaultUploadFileContentType;
}
else if (contentType.StartsWith("multipart/", StringComparison.OrdinalIgnoreCase))
{
throw new WebException(SR.net_webclient_Multipart);
}
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
int buffSize = DefaultCopyBufferLength;
_contentLength = -1;
if (string.Equals(_method, "POST", StringComparison.Ordinal))
{
if (needsHeaderAndBoundary)
{
string boundary = $"---------------------{DateTime.Now.Ticks:x}";
headers[HttpKnownHeaderNames.ContentType] = UploadFileContentType + "; boundary=" + boundary;
string formHeader =
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + Path.GetFileName(fileName) + "\"\r\n" + // TODO: Should the filename path be encoded?
"Content-Type: " + contentType + "\r\n" +
"\r\n";
formHeaderBytes = Encoding.UTF8.GetBytes(formHeader);
boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
}
else
{
formHeaderBytes = Array.Empty<byte>();
boundaryBytes = Array.Empty<byte>();
}
if (fs.CanSeek)
{
_contentLength = fs.Length + formHeaderBytes.Length + boundaryBytes.Length;
buffSize = (int)Math.Min(DefaultCopyBufferLength, fs.Length);
}
}
else
{
headers[HttpKnownHeaderNames.ContentType] = contentType;
formHeaderBytes = null;
boundaryBytes = null;
if (fs.CanSeek)
{
_contentLength = fs.Length;
buffSize = (int)Math.Min(DefaultCopyBufferLength, fs.Length);
}
}
buffer = new byte[buffSize];
}
public byte[] UploadFile(string address, string fileName) =>
UploadFile(GetUri(address), fileName);
public byte[] UploadFile(Uri address, string fileName) =>
UploadFile(address, null, fileName);
public byte[] UploadFile(string address, string? method, string fileName) =>
UploadFile(GetUri(address), method, fileName);
public byte[] UploadFile(Uri address, string? method, string fileName)
{
ArgumentNullException.ThrowIfNull(address);
ArgumentNullException.ThrowIfNull(fileName);
method ??= MapToDefaultMethod(address);
FileStream? fs = null;
WebRequest? request = null;
StartOperation();
try
{
_method = method;
byte[]? formHeaderBytes = null, boundaryBytes = null, buffer;
Uri uri = GetUri(address);
bool needsHeaderAndBoundary = (uri.Scheme != Uri.UriSchemeFile);
OpenFileInternal(needsHeaderAndBoundary, fileName, out fs, out buffer, ref formHeaderBytes, ref boundaryBytes);
request = _webRequest = GetWebRequest(uri);
return UploadBits(request, fs, buffer, 0, formHeaderBytes, boundaryBytes);
}
catch (Exception e)
{
fs?.Close();
if (e is OutOfMemoryException) throw;
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
finally
{
EndOperation();
}
}
private byte[] GetValuesToUpload(NameValueCollection data)
{
WebHeaderCollection headers = Headers;
string? contentType = headers[HttpKnownHeaderNames.ContentType];
if (contentType != null && !string.Equals(contentType, UploadValuesContentType, StringComparison.OrdinalIgnoreCase))
{
throw new WebException(SR.net_webclient_ContentType);
}
headers[HttpKnownHeaderNames.ContentType] = UploadValuesContentType;
string delimiter = string.Empty;
var values = new StringBuilder();
foreach (string? name in data.AllKeys)
{
values.Append(delimiter);
values.Append(UrlEncode(name));
values.Append('=');
values.Append(UrlEncode(data[name]));
delimiter = "&";
}
byte[] buffer = Encoding.ASCII.GetBytes(values.ToString());
_contentLength = buffer.Length;
return buffer;
}
public byte[] UploadValues(string address, NameValueCollection data) =>
UploadValues(GetUri(address), null, data);
public byte[] UploadValues(Uri address, NameValueCollection data) =>
UploadValues(address, null, data);
public byte[] UploadValues(string address, string? method, NameValueCollection data) =>
UploadValues(GetUri(address), method, data);
public byte[] UploadValues(Uri address, string? method, NameValueCollection data)
{
ArgumentNullException.ThrowIfNull(address);
ArgumentNullException.ThrowIfNull(data);
method ??= MapToDefaultMethod(address);
WebRequest? request = null;
StartOperation();
try
{
byte[] buffer = GetValuesToUpload(data);
_method = method;
request = _webRequest = GetWebRequest(GetUri(address));
return UploadBits(request, null, buffer, 0, null, null);
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
finally
{
EndOperation();
}
}
public string UploadString(string address, string data) =>
UploadString(GetUri(address), null, data);
public string UploadString(Uri address, string data) =>
UploadString(address, null, data);
public string UploadString(string address, string? method, string data) =>
UploadString(GetUri(address), method, data);
public string UploadString(Uri address, string? method, string data)
{
ArgumentNullException.ThrowIfNull(address);
ArgumentNullException.ThrowIfNull(data);
method ??= MapToDefaultMethod(address);
StartOperation();
try
{
WebRequest request;
byte[] requestData = Encoding.GetBytes(data);
byte[] responseData = UploadDataInternal(address, method, requestData, out request);
return GetStringUsingEncoding(request, responseData);
}
finally
{
EndOperation();
}
}
public string DownloadString(string address) =>
DownloadString(GetUri(address));
public string DownloadString(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
StartOperation();
try
{
WebRequest request;
byte[] data = DownloadDataInternal(address, out request);
return GetStringUsingEncoding(request, data);
}
finally
{
EndOperation();
}
}
private static void AbortRequest(WebRequest? request)
{
try { request?.Abort(); }
catch (Exception exception) when (!(exception is OutOfMemoryException)) { }
}
private void CopyHeadersTo(WebRequest request)
{
if (_headers == null)
{
return;
}
var hwr = request as HttpWebRequest;
if (hwr == null)
{
return;
}
string? accept = _headers[HttpKnownHeaderNames.Accept];
string? connection = _headers[HttpKnownHeaderNames.Connection];
string? contentType = _headers[HttpKnownHeaderNames.ContentType];
string? expect = _headers[HttpKnownHeaderNames.Expect];
string? referrer = _headers[HttpKnownHeaderNames.Referer];
string? userAgent = _headers[HttpKnownHeaderNames.UserAgent];
string? host = _headers[HttpKnownHeaderNames.Host];
_headers.Remove(HttpKnownHeaderNames.Accept);
_headers.Remove(HttpKnownHeaderNames.Connection);
_headers.Remove(HttpKnownHeaderNames.ContentType);
_headers.Remove(HttpKnownHeaderNames.Expect);
_headers.Remove(HttpKnownHeaderNames.Referer);
_headers.Remove(HttpKnownHeaderNames.UserAgent);
_headers.Remove(HttpKnownHeaderNames.Host);
request.Headers = _headers;
if (!string.IsNullOrEmpty(accept))
{
hwr.Accept = accept;
}
if (!string.IsNullOrEmpty(connection))
{
hwr.Connection = connection;
}
if (!string.IsNullOrEmpty(contentType))
{
hwr.ContentType = contentType;
}
if (!string.IsNullOrEmpty(expect))
{
hwr.Expect = expect;
}
if (!string.IsNullOrEmpty(referrer))
{
hwr.Referer = referrer;
}
if (!string.IsNullOrEmpty(userAgent))
{
hwr.UserAgent = userAgent;
}
if (!string.IsNullOrEmpty(host))
{
hwr.Host = host;
}
}
private Uri GetUri(string address)
{
ArgumentNullException.ThrowIfNull(address);
Uri? uri;
if (_baseAddress != null)
{
if (!Uri.TryCreate(_baseAddress, address, out uri))
{
return new Uri(Path.GetFullPath(address));
}
}
else if (!Uri.TryCreate(address, UriKind.Absolute, out uri))
{
return new Uri(Path.GetFullPath(address));
}
return GetUri(uri);
}
private Uri GetUri(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
Uri? uri = address;
if (!address.IsAbsoluteUri && _baseAddress != null && !Uri.TryCreate(_baseAddress, address, out uri))
{
return address;
}
if (string.IsNullOrEmpty(uri.Query) && _requestParameters != null)
{
var sb = new StringBuilder();
string delimiter = string.Empty;
for (int i = 0; i < _requestParameters.Count; ++i)
{
sb.Append(delimiter).Append(_requestParameters.AllKeys[i]).Append('=').Append(_requestParameters[i]);
delimiter = "&";
}
uri = new UriBuilder(uri) { Query = sb.ToString() }.Uri;
}
return uri;
}
private byte[]? DownloadBits(WebRequest request, Stream writeStream)
{
try
{
WebResponse response = _webResponse = GetWebResponse(request);
long contentLength = response.ContentLength;
byte[] copyBuffer = new byte[contentLength == -1 || contentLength > DefaultDownloadBufferLength ? DefaultDownloadBufferLength : contentLength];
if (writeStream is ChunkedMemoryStream)
{
if (contentLength > int.MaxValue)
{
throw new WebException(SR.net_webstatus_MessageLengthLimitExceeded, WebExceptionStatus.MessageLengthLimitExceeded);
}
writeStream.SetLength(copyBuffer.Length);
}
using (Stream readStream = response.GetResponseStream())
{
if (readStream != null)
{
int bytesRead;
while ((bytesRead = readStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0)
{
writeStream.Write(copyBuffer, 0, bytesRead);
}
}
}
return (writeStream as ChunkedMemoryStream)?.ToArray();
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
writeStream?.Close();
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
}
private async void DownloadBitsAsync(
WebRequest request, Stream writeStream,
AsyncOperation asyncOp, Action<byte[]?, Exception?, AsyncOperation> completionDelegate)
{
Debug.Assert(_progress != null, "ProgressData should have been initialized");
Debug.Assert(asyncOp != null);
Exception? exception = null;
try
{
WebResponse response = _webResponse = await GetWebResponseTaskAsync(request).ConfigureAwait(false);
long contentLength = response.ContentLength;
byte[] copyBuffer = new byte[contentLength == -1 || contentLength > DefaultDownloadBufferLength ? DefaultDownloadBufferLength : contentLength];
if (writeStream is ChunkedMemoryStream)
{
if (contentLength > int.MaxValue)
{
throw new WebException(SR.net_webstatus_MessageLengthLimitExceeded, WebExceptionStatus.MessageLengthLimitExceeded);
}
writeStream.SetLength(copyBuffer.Length);
}
if (contentLength >= 0)
{
_progress.TotalBytesToReceive = contentLength;
}
using (writeStream)
using (Stream readStream = response.GetResponseStream())
{
if (readStream != null)
{
while (true)
{
int bytesRead = await readStream.ReadAsync(new Memory<byte>(copyBuffer)).ConfigureAwait(false);
if (bytesRead == 0)
{
break;
}
_progress.BytesReceived += bytesRead;
if (_progress.BytesReceived != _progress.TotalBytesToReceive)
{
PostProgressChanged(asyncOp, _progress);
}
await writeStream.WriteAsync(new ReadOnlyMemory<byte>(copyBuffer, 0, bytesRead)).ConfigureAwait(false);
}
}
if (_progress.TotalBytesToReceive < 0)
{
_progress.TotalBytesToReceive = _progress.BytesReceived;
}
PostProgressChanged(asyncOp, _progress);
}
completionDelegate((writeStream as ChunkedMemoryStream)?.ToArray(), null, asyncOp);
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
exception = GetExceptionToPropagate(e);
AbortRequest(request);
writeStream?.Close();
}
finally
{
if (exception != null)
{
completionDelegate(null, exception, asyncOp);
}
}
}
private byte[] UploadBits(
WebRequest request, Stream? readStream, byte[] buffer, int chunkSize,
byte[]? header, byte[]? footer)
{
try
{
if (request.RequestUri.Scheme == Uri.UriSchemeFile)
{
header = footer = null;
}
using (Stream writeStream = request.GetRequestStream())
{
if (header != null)
{
writeStream.Write(header, 0, header.Length);
}
if (readStream != null)
{
using (readStream)
{
while (true)
{
int bytesRead = readStream.Read(buffer, 0, buffer.Length);
if (bytesRead <= 0)
break;
writeStream.Write(buffer, 0, bytesRead);
}
}
}
else
{
for (int pos = 0; pos < buffer.Length;)
{
int toWrite = buffer.Length - pos;
if (chunkSize != 0 && toWrite > chunkSize)
{
toWrite = chunkSize;
}
writeStream.Write(buffer, pos, toWrite);
pos += toWrite;
}
}
if (footer != null)
{
writeStream.Write(footer, 0, footer.Length);
}
}
return DownloadBits(request, new ChunkedMemoryStream())!;
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
AbortRequest(request);
if (e is WebException || e is SecurityException) throw;
throw new WebException(SR.net_webclient, e);
}
}
private async void UploadBitsAsync(
WebRequest request, Stream? readStream, byte[] buffer, int chunkSize,
byte[]? header, byte[]? footer,