forked from nanoframework/System.Net.Http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystem.Net.HttpWebRequest.cs
More file actions
2047 lines (1792 loc) · 75.7 KB
/
System.Net.HttpWebRequest.cs
File metadata and controls
2047 lines (1792 loc) · 75.7 KB
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
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Net
{
using System;
using System.Collections;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Diagnostics;
/// <summary>
/// This is the class that we use to create HTTP and requests.
/// Used to register prefix "http" with WEB Request class.
/// </summary>
internal class HttpRequestCreator : IWebRequestCreate
{
internal HttpRequestCreator()
{
}
/// <summary>
/// Creates an HttpWebRequest. We register
/// for http, https, ws and wss URLs, and this method is called when a request
/// needs to be created for one of those.
/// </summary>
/// <param name="Url">Url for request being created.</param>
/// <returns>The newly created HttpWebRequest.</returns>
public WebRequest Create(Uri Url)
{
return new HttpWebRequest(Url);
}
} // class HttpRequestCreator
/// <summary>
/// Provides an HTTP-specific implementation of the <see cref="WebRequest"/> class.
/// </summary>
/// <remarks>This class does the main work of the request: it collects the header information
/// from the user, exposes the Stream for outgoing entity data, and processes the incoming
/// request.</remarks>
public class HttpWebRequest : WebRequest
{
/// <summary>
/// Array list of connected streams.
/// This is static list, keeps all "stay live" sockets.
/// </summary>
internal static ArrayList m_ConnectedStreams;
/// <summary>
/// Timer that checks on open connections and closes them if they are
/// idle for a long time.
/// </summary>
static Timer m_DropOldConnectionsTimer;
/// <summary>
/// If a response was created then Dispose on the Request will not dispose the underlying stream.
/// </summary>
private bool m_responseCreated;
/// <summary>
/// Timer callback. Called periodically and closes all connections that
/// are idle for long time.
/// </summary>
/// <param name="unused">Unused</param>
static private void CheckPersistentConnections(object unused)
{
// Persistent connections have not been properly implemented yet.
int count = m_ConnectedStreams.Count;
// The fastest way to exit out - if there are no sockets in the list - exit out.
if (count > 0)
{
DateTime curTime = DateTime.UtcNow;
lock (m_ConnectedStreams)
{
count = m_ConnectedStreams.Count;
for (int i = count - 1; i >= 0; i--)
{
InputNetworkStreamWrapper streamWrapper = (InputNetworkStreamWrapper)m_ConnectedStreams[i];
TimeSpan timePassed = curTime - streamWrapper.m_lastUsed;
// If the socket is old, then close and remove from the list.
if (timePassed.TotalMilliseconds > HttpConstants.DefaultKeepAliveMilliseconds)
{
m_ConnectedStreams.RemoveAt(i);
// Closes the socket to release resources.
streamWrapper.Dispose();
}
}
// Keep the timer going for another DefaultKeepAliveMilliseconds if we still have persistent connections in m_ConnectedStreams.
// Otherwise, do nothing. The timer won't be fired again.
if (m_ConnectedStreams.Count > 0)
{
m_DropOldConnectionsTimer.Change(HttpConstants.DefaultKeepAliveMilliseconds, System.Threading.Timeout.Infinite);
}
}
}
}
/// <summary>
/// Registers <itemref>HttpRequestCreator</itemref> as the creator for the "http" prefix.
/// </summary>
static HttpWebRequest()
{
// The static constructor of the base class does not get called before the derived static constructor
// so you have to make sure the base class gets initialized in any case if you want to use "RegisterPrefix"
Initialize();
// Creates instance of HttpRequestCreator. HttpRequestCreator creates HttpWebRequest
HttpRequestCreator Creator = new HttpRequestCreator();
// Register prefix. HttpWebRequest handles both http and https
RegisterPrefix("http:", Creator);
RegisterPrefix("https:", Creator);
if (m_ConnectedStreams == null)
{
// Creates new list for connected sockets.
m_ConnectedStreams = new ArrayList();
m_DropOldConnectionsTimer = new Timer(CheckPersistentConnections, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
}
}
/// <summary>
/// Closes a response stream, if present.
/// </summary>
/// <param name="disposing">Not used.</param>
protected override void Dispose(bool disposing)
{
if (m_requestStream != null)
{
if (!m_responseCreated)
{
RemoveStreamFromPool(m_requestStream);
m_requestStream.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// The length in KB of the default maximum for response headers
/// received.
/// </summary>
/// <remarks>
/// The default configuration file sets this value to 4 kilobytes.
/// </remarks>
static int defaultMaxResponseHeadersLen = 4;
/// <summary>
/// Default delay on the Stream.Read and Stream.Write operations
/// </summary>
private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes
/// <summary>
/// Delegate that can be called on Continue Response
/// </summary>
private HttpContinueDelegate m_continueDelegate;
/// <summary>
/// HTTP verb.
/// </summary>
private string m_method;
/// <summary>
/// The Headers for the HTTP request.
/// </summary>
private WebHeaderCollection m_httpRequestHeaders;
/// <summary>
/// Controls how writes are handled.
/// </summary>
private HttpWriteMode m_httpWriteMode;
/// <summary>
/// The URI that we do the request for.
/// </summary>
private Uri m_originalUrl;
/// <summary>
/// Content length of the request message on POST.
/// </summary>
private long m_contentLength;
/// <summary>
/// The HTTP version for this request.
/// </summary>
private Version m_version;
/// <summary>
/// Timeout for Read And Write on the Stream that we return through
/// GetResponse().GetResponseStream() and GetRequestStream()
/// </summary>
private int m_readWriteTimeout;
/// <summary>
/// Proxy to use for connection.
/// </summary>
private IWebProxy m_proxy;
/// <summary>
/// Select <see cref="SslProtocol"/> to be used for requests. The default is <see cref="SslProtocol.None"/> to force setting it.
/// </summary>
private SslProtocols m_sslProtocols = SslProtocols.None;
/// <summary>
/// Whether to use persistent connections.
/// </summary>
private bool m_keepAlive;
/// <summary>
/// An array of certificates used to verify servers that support https.
/// </summary>
/// <remarks>
/// The client application sets these certificates to the
/// <b>HttpWebRequest</b>. When the server certificate is received, it
/// is validated with certificates in this array.
/// </remarks>
X509Certificate m_caCert;
/// <summary>
/// Client certificate used to authenticate with server.
/// </summary>
internal X509Certificate _clientCert;
/// <summary>
/// The number of people using the connection. Must reference-count this
/// stuff. Except reference counting is apparently insufficient. I'm going to flag each section
/// that uses the parser with a constant, and twiddle the flags for
/// adding and removing connections.
/// </summary>
internal const int k_noConnection = 0x0;
private const int k_parserFlag = 0x1;
private const int k_writeStreamFlag = 0x2;
private const int k_readStreamFlag = 0x4;
private const int k_abortFlag = 0x8;
internal int m_connectionUsers = 0;
/// <summary>
/// Static instance of decoder to convert received bytes from network
/// stream into text of the response line and WEB headers.
/// </summary>
static private Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder();
/// <summary>
/// Invalid characters that cannot be found in a valid method-verb.
/// </summary>
private static readonly char[] k_invalidMethodChars =
new char[]{' ',
'\r',
'\t',
'\n'};
/// <summary>
/// Exposes this property from <see cref="SslStream.SslVerification"/>.
/// </summary>
private SslVerification _sslVerification;
/// <summary>
/// The maximum length, in kilobytes (1024 bytes), of the response
/// headers.
/// </summary>
private int m_maxResponseHeadersLen = defaultMaxResponseHeadersLen;
/// <summary>
/// The response from the server.
/// </summary>
private HttpStatusCode m_responseStatus = (HttpStatusCode)0;
/// <summary>
/// true if we have a response, or a transport error while constructing the response
/// </summary>
private bool m_responseComplete = false;
/// <summary>
/// This is non-null if there was an error. If this is true, then there is no valid HttpWebResponse.
/// </summary>
private WebException m_errorResponse = null;
/// <summary>
/// Buffer size for reading from the server
/// </summary>
private const int k_readBlockLength = 2048;
/// <summary>
/// This is the maximum amount of data which can be buffered at any time
/// and have a failed match. In other words, if we receive this much
/// data, and can't parse it in any useful way, assume an error.
/// </summary>
private const int k_maximumBufferSize = 8192;
/// <summary>
/// True if the request has been started, false otherwise. Disables
/// setting of many header properties.
/// </summary>
private bool m_requestSent;
/// <summary>
/// This is the request stream, if it has been created.
/// </summary>
private InputNetworkStreamWrapper m_requestStream;
/// <summary>
/// Whether or not data should be buffered when sent.
/// Data is always buffered though (given redirects and stuff).
/// </summary>
private bool m_allowWriteStreamBuffering;
/// <summary>
/// The timeout value for this request.
/// </summary>
private int m_timeout;
/// <summary>
/// Keep NetworkCredential if user have send user name and password.
/// </summary>
private NetworkCredential m_NetworkCredentials;
/// <summary>
/// Gets or sets the timeout value in milliseconds for the
/// <see cref="GetResponse"/> and
/// <see cref="GetRequestStream"/> methods.
/// </summary>
/// <value>The number of milliseconds to wait before the request times
/// out. The default is 100,000 milliseconds (100 seconds).</value>
/// <remarks>
/// Overrides the <see cref="WebRequest.Timeout"/> property
/// of <itemref>WebRequest</itemref>.</remarks>
public override int Timeout
{
get
{
return m_timeout;
}
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException("value");
}
m_timeout = value;
}
}
/// <summary>
/// Set or Get NetworkCredential if user have send user name and password.
/// </summary>
public NetworkCredential Credentials
{
get { return m_NetworkCredentials; }
set { m_NetworkCredentials = value; }
}
/// <summary>
/// Gets or sets the root CA certificate used to authenticate with https
/// servers. This certificate is used only for https connections;
/// http connections do not require this.
/// </summary>
public X509Certificate HttpsAuthentCert
{
get { return m_caCert; }
set { m_caCert = value; }
}
/// <summary>
/// Gets or sets
/// </summary>
public SslVerification SslVerification
{
get { return _sslVerification; }
set { _sslVerification = value; }
}
/// <summary>
/// Gets or sets the TLS/SSL protocol used by the <see cref="HttpWebRequest"/> class.
/// </summary>
/// <value>
/// One of the values defined in the <see cref="Security.SslProtocols"/> enumeration.
/// </value>
/// <remarks>
/// Setting this property is mandatory when performing HTTPS requests, otherwise the authentication will fail.
///
/// This property is specific to nanoFramework. There is no equivalent in the .NET API.
/// </remarks>
public SslProtocols SslProtocols
{
get { return m_sslProtocols; }
set { m_sslProtocols = value; }
}
/// <summary>
/// Gets or sets a timeout in milliseconds when writing to or reading
/// from a stream.
/// </summary>
/// <value>The number of milliseconds before the writing or reading
/// times out. The default value is 300,000 milliseconds (5 minutes).
/// </value>
/// <remarks>This property is used to control the timeout when calling
/// <see cref="Stream.Read(byte[], int, int)"/> and <see cref="Stream.Write"/>.
/// This property affects <itemref>Stream</itemref>s returned from
/// GetResponse().<see cref="WebResponse.GetResponseStream"/>()
/// and
/// GetResponse().<see cref="GetRequestStream"/>().
/// </remarks>
public int ReadWriteTimeout
{
get
{
return m_readWriteTimeout;
}
set
{
// we can't change timeouts after the request has been sent
if (m_requestSent)
throw new InvalidOperationException("Cannot change timeout after request submitted ");
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException("value");
}
m_readWriteTimeout = value;
}
}
/// <summary>
/// The HTTP status code returned by the server.
/// </summary>
internal HttpStatusCode ResponseStatusCode
{
get
{
return m_responseStatus;
}
}
/// <summary>
/// Return if error is present in response.
/// </summary>
/// <returns>true if error happened, false otherwise</returns>
internal bool hasError()
{
return m_errorResponse != null;
}
/// <summary>
/// Gets the original Uniform Resource Identifier (URI) of the request.
/// </summary>
/// <remarks>
/// The URI object was created by the constructor and is always
/// non-null. The URI object will always be the base URI, because
/// automatic re-directs aren't supported.
/// </remarks>
/// <value>A Uri that contains the URI of the Internet resource passed
/// to the WebRequest.<see cref="WebRequest.Create(Uri)"/> method.
/// </value>
public override Uri RequestUri
{
get
{
return m_originalUrl;
}
}
/// <summary>
/// Gets the URI for this request.
/// </summary>
/// <value>A <itemref>Uri</itemref> that identifies the Internet
/// resource that actually responds to the request. The default is the
/// URI used by the
/// WebRequest.<see cref="WebRequest.Create(Uri)"/> method to
/// initialize the request.
/// </value>
/// <remarks>
/// This value is always the same as the
/// <see cref="RequestUri"/>
/// property, because automatic re-direction isn't supported.
/// </remarks>
public Uri Address
{
get
{
return m_originalUrl;
}
}
/// <summary>
/// Gets or sets a value that indicates whether to buffer the data sent
/// to the Internet resource.
/// </summary>
/// <value><itemref>true</itemref> to enable buffering of the data sent
/// to the Internet resource; <b>false</b> to disable buffering. The
/// default is <b>true</b>.</value>
public bool AllowWriteStreamBuffering
{
get
{
return m_allowWriteStreamBuffering;
}
set
{
m_allowWriteStreamBuffering = value;
}
}
/// <summary>
/// Gets or sets the <b>Content-Length</b> of the request entity body.
/// </summary>
/// <value>The number of bytes of data to send to the Internet resource.
/// The default is -1, which indicates the property has not been set and
/// that there is no request data to send.</value>
/// <remarks>
/// Getting this property returns the last value set, or -1 if no value
/// has been set. Setting it sets the content length, and the
/// application must write that much data to the stream. This property
/// interacts with
/// <b>HttpWebRequest</b>.<see cref="SendChunked"/>.
/// </remarks>
public override long ContentLength
{
get
{
return m_contentLength;
}
set
{
//no race. Don't need interlocked
if (true == m_requestSent)
throw new InvalidOperationException();
if (value < 0)
throw new ArgumentOutOfRangeException("Content length cannot be negative: " + value);
m_contentLength = value;
//if a content length is set, then we cannot send chunked data.
m_httpWriteMode = HttpWriteMode.Write;
}
}
/// <summary>
/// Gets or sets the delegate used to signal on Continue callback.
/// </summary>
/// <value>A delegate that implements the callback method that executes
/// when an HTTP Continue response is returned from the Internet
/// resource. The default value is <b>null</b>.</value>
/// <remarks>
/// This property gets or sets the delegate method called when an HTTP
/// 100-continue response is received from the Internet resource.
/// </remarks>
public HttpContinueDelegate ContinueDelegate
{
get { return m_continueDelegate; }
set { m_continueDelegate = value; }
}
/// <summary>
/// Gets a value that indicates whether the request should follow
/// redirection responses. This value is always
/// <itemref>false</itemref>, because Autodirect isn't supported.
/// </summary>
/// <value>This value is always <itemref>false</itemref>, because
/// Autodirect isn't supported.</value>
public bool AllowAutoRedirect
{
get
{
return false;
}
}
/// <summary>
/// Gets the maximum number of automatic redirections. This value is
/// always zero, because auto-redirection isn't supported.
/// </summary>
/// <value>This value is always zero, because auto-redirection isn't
/// supported.</value>
public int MaximumAutomaticRedirections
{
get
{
return 0;
}
}
/// <summary>
/// Gets or sets the HTTP method of this request.
/// </summary>
/// <value>The request method to use to contact the Internet resource.
/// The default value is GET.</value>
/// <remarks>
/// This method represents the initial origin verb, which is unchanged
/// and unaffected by redirects.
/// </remarks>
public override string Method
{
get
{
return m_method;
}
set
{
if (ValidationHelper.IsBlankString(value))
{
throw new ArgumentException("Blank Method Set: " + value);
}
if (value.IndexOfAny(k_invalidMethodChars) != -1)
{
throw new ArgumentException("Invalid Method Set: " + value);
}
m_method = value;
}
}
/// <summary>
/// Gets or sets whether to use a persistent connection, if available.
/// </summary>
/// <value><b>true</b> if the request to the Internet resource should
/// contain a <b>Connection</b> HTTP header with the value Keep-alive;
/// otherwise, <b>false</b>. The default is <b>true</b>.</value>
public bool KeepAlive
{
get
{
return m_keepAlive;
}
set
{
m_keepAlive = value;
}
}
/// <summary>
/// Gets or sets the maximum allowed length of the response headers.
/// </summary>
/// <value>The length, in kilobytes (1024 bytes), of the response
/// headers.</value>
/// <remarks>
/// The length of the response header includes the response status line
/// and any extra control characters that are received as part of HTTP
/// protocol. A value of -1 means no limit is imposed on the response
/// headers; a value of 0 means that all requests fail. If this
/// property is not explicitly set, it defaults to the value of the
/// <see cref="DefaultMaximumResponseHeadersLength"/>
/// property.
/// </remarks>
public int MaximumResponseHeadersLength
{
get { return m_maxResponseHeadersLen; }
set
{
if (value <= 0 && value != -1)
{
throw new ArgumentOutOfRangeException();
}
m_maxResponseHeadersLen = value;
}
}
/// <summary>
/// Gets or sets the default maximum allowed length of the response
/// headers.
/// </summary>
/// <value>The default maximum allowed length of the response headers.
/// </value>
/// <remarks>
/// On creation of an <itemref>HttpWebRequest</itemref> instance, this
/// value is used for the
/// <see cref="MaximumResponseHeadersLength"/>
/// property.
/// </remarks>
public static int DefaultMaximumResponseHeadersLength
{
get { return defaultMaxResponseHeadersLen; }
set
{
if (value <= 0 && value != -1)
{
throw new ArgumentOutOfRangeException();
}
defaultMaxResponseHeadersLen = value;
}
}
/// <summary>
/// A collection of HTTP headers stored as name/value pairs.
/// </summary>
/// <value>A <b>WebHeaderCollection</b> that contains the name/value
/// pairs that make up the headers for the HTTP request.</value>
/// <remarks>
/// The following header values are set through properties on the
/// <itemref>HttpWebRequest</itemref> class: Accept, Connection,
/// Content-Length, Content-Type, Expect, Range, Referer,
/// Transfer-Encoding, and User-Agent. Trying to set these header
/// values by using
/// <b>WebHeaderCollection.<see cref="WebHeaderCollection.Add(string, string)"/>()</b>
/// will raise an exception. Date and Host are set internally.
/// </remarks>
public override WebHeaderCollection Headers
{
get
{
return m_httpRequestHeaders;
}
set
{
// we can't change headers after they've already been sent
if (m_requestSent)
throw new InvalidOperationException("Cannot change headers after request submitted");
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders =
new WebHeaderCollection(true);
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
for (int i = 0; i < webHeaders.AllKeys.Length; i++)
{
newWebHeaders.Add(webHeaders.AllKeys[i], webHeaders[webHeaders.AllKeys[i]]);
}
m_httpRequestHeaders = newWebHeaders;
}
}
/// <summary>
/// Gets or sets the proxy for the request.
/// </summary>
/// <value>The <see cref="IWebProxy"/> object to use to proxy
/// the request. <b>null</b> indicates that no proxy will be used.</value>
public override IWebProxy Proxy
{
get { return m_proxy; }
set
{
if (m_requestSent)
throw new InvalidOperationException("Cannot change proxy after request submitted");
if (value == null)
throw new ArgumentNullException();
m_proxy = value;
}
}
/// <summary>
/// Gets or sets the state of chunk transfer send mode.
/// </summary>
/// <value><b>true</b> to send data to the Internet resource in
/// segments; otherwise, <b>false</b>. The default value is
/// <b>false</b>.</value>
/// <remarks>
/// If <itemref>true</itemref>, bits are uploaded and written using the
/// <b>Chunked</b> property of <b>HttpWriteMode</b>.
/// </remarks>
public bool SendChunked
{
get { return m_httpWriteMode == HttpWriteMode.Chunked; }
set
{
//no race. Don't need interlocked
if (true == m_requestSent)
{
throw new InvalidOperationException("Cannot set \"chunked\" after request submitted");
}
if (value)
{
m_httpWriteMode = HttpWriteMode.Chunked;
}
else
{
if (m_contentLength >= 0)
{
m_httpWriteMode = HttpWriteMode.Write;
}
else
{
m_httpWriteMode = HttpWriteMode.None;
}
}
}
}
/// <summary>
/// Gets or sets the HTTP protocol version for this request.
/// </summary>
/// <value>The HTTP version to use for the request. The default is
/// <see cref="HttpVersion.Version11"/>.</value>
public Version ProtocolVersion
{
get
{
return m_version;
}
set
{
if (!value.Equals(HttpVersion.Version10) &&
!value.Equals(HttpVersion.Version11))
{
throw new ArgumentException("Invalid HTTP Verion: " + value);
}
m_version = new Version(value.Major, value.Minor);
}
}
/// <summary>
/// Private method for removing duplicate code which removes and adds
/// headers that are marked private.
/// </summary>
/// <param name="HeaderName">The name of the HTTP header.</param>
/// <param name="value">The value of the HTTP header.</param>
private void SetSpecialHeaders(String HeaderName, String value)
{
value = WebHeaderCollection.CheckBadChars(value, true);
m_httpRequestHeaders.RemoveInternal(HeaderName);
if (value != null && value.Length != 0)
{
m_httpRequestHeaders.AddInternal(HeaderName, value);
}
}
/// <summary>
/// Gets or sets the type of the entity body (the value of the content
/// type).
/// </summary>
/// <value>The value of the <b>Content-type</b> HTTP header. The
/// default value is <b>null</b>.</value>
/// <remarks>
/// Setting to <b>null</b> clears the content-type.
/// </remarks>
public override String ContentType
{
get
{
return m_httpRequestHeaders[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
/// <summary>
/// Gets or sets the <b>TransferEncoding</b> HTTP header.
/// </summary>
/// <value>The value of the <b>Transfer-encoding</b> HTTP header. The
/// default value is <b>null</b>.</value>
/// <remarks>
/// <b>null</b> clears the transfer encoding except for the
/// <b>Chunked</b> setting.
/// </remarks>
public String TransferEncoding
{
get
{
return m_httpRequestHeaders[HttpKnownHeaderNames.TransferEncoding];
}
set
{
bool fChunked;
// on blank string, remove current header
if (ValidationHelper.IsBlankString(value))
{
// if the value is blank, then remove the header
m_httpRequestHeaders.RemoveInternal(HttpKnownHeaderNames.TransferEncoding);
return;
}
// if not, check if the user is trying to set chunked:
string newValue = value.ToLower();
fChunked = (newValue.IndexOf("chunked") != -1);
// prevent them from adding chunked, or from adding an Encoding
// without turing on chunked, the reason is due to the HTTP
// Spec which prevents additional encoding types from being
// used without chunked
if (fChunked)
{
throw new ArgumentException("Cannot add \"Encoding\" and set \"chunked\"");
}
else if (m_httpWriteMode != HttpWriteMode.Chunked)
{
throw new InvalidOperationException("Need HttpWriteMode.Chunked to be current mode");
}
else
{
m_httpRequestHeaders.CheckUpdate(HttpKnownHeaderNames.TransferEncoding, value);
}
}
}
/// <summary>
/// Gets or sets the value of the <b>Accept</b> HTTP header.
/// </summary>
/// <value>The value of the <b>Accept</b> HTTP header. The default
/// value is <b>null</b>.</value>
public String Accept
{
get { return m_httpRequestHeaders[HttpKnownHeaderNames.Accept]; }
set { SetSpecialHeaders(HttpKnownHeaderNames.Accept, value); }
}
/// <summary>
/// Gets or sets the value of the <b>Referer</b> HTTP header.
/// </summary>
/// <value>The value of the <b>Referer</b> HTTP header. The default
/// value is <b>null</b>.</value>
/// <remarks>This header value is misspelled intentionally.</remarks>
public String Referer
{
get { return m_httpRequestHeaders[HttpKnownHeaderNames.Referer]; }
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Referer, value);
}
}
/// <summary>
/// Gets or sets the value of the <b>User-Agent</b> HTTP header.
/// </summary>
/// <value>The value of the <b>User-agent</b> HTTP header. The default
/// value is <b>null</b>.</value>
public String UserAgent
{
get { return m_httpRequestHeaders[HttpKnownHeaderNames.UserAgent]; }
set
{
SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value);
}
}
/// <summary>
/// Gets or sets the value of the <b>Expect</b> HTTP header.
/// </summary>
/// <value>The contents of the <b>Expect</b> HTTP header. The default
/// value is <b>null</b>.</value>
/// <remarks>When setting this property, <b>null</b> clears the
/// <b>Expect</b> (except for the 100-continue value).</remarks>
public String Expect
{
get { return m_httpRequestHeaders[HttpKnownHeaderNames.Expect]; }
set
{
// on blank string, remove current header
if (ValidationHelper.IsBlankString(value))
{
m_httpRequestHeaders.RemoveInternal(HttpKnownHeaderNames.Expect);
return;
}
m_httpRequestHeaders.CheckUpdate(HttpKnownHeaderNames.Expect, value);
}
}
/// <summary>
/// Gets the <itemref>IfModifiedSince</itemref> value of
/// <itemref>HttpKnownHeaderNames</itemref>.
/// </summary>
/// <value>A <see cref="DateTime"/> that contains the contents of
/// the <b>If-Modified-Since</b> HTTP header. The default value is the