2 // System.Net.HttpWebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2002 Lawrence Pit
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // (c) 2004 Novell, Inc. (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections;
36 using System.Configuration;
38 using System.Net.Sockets;
39 using System.Runtime.Remoting.Messaging;
40 using System.Runtime.Serialization;
41 using System.Security.Cryptography.X509Certificates;
43 using System.Threading;
48 public class HttpWebRequest : WebRequest, ISerializable
53 bool allowAutoRedirect = true;
54 bool allowBuffering = true;
55 X509CertificateCollection certificates;
56 string connectionGroup;
57 long contentLength = -1;
58 HttpContinueDelegate continueDelegate;
59 CookieContainer cookieContainer;
60 ICredentials credentials;
64 WebHeaderCollection webHeaders = new WebHeaderCollection (true);
65 bool keepAlive = true;
66 int maxAutoRedirect = 50;
67 string mediaType = String.Empty;
68 string method = "GET";
69 string initialMethod = "GET";
70 bool pipelined = true;
73 Version version = HttpVersion.Version11;
74 Version actualVersion;
77 ServicePoint servicePoint;
80 WebConnectionStream writeStream;
81 HttpWebResponse webResponse;
82 WebAsyncResult asyncWrite;
83 WebAsyncResult asyncRead;
84 EventHandler abortHandler;
86 bool gotRequestStream;
92 bool getResponseCalled;
94 object locker = new object ();
96 int maxResponseHeadersLength;
97 static int defaultMaxResponseHeadersLength;
98 int readWriteTimeout = 300000; // ms
101 static HttpWebRequest ()
103 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
104 defaultMaxResponseHeadersLength = 64 * 1024;
105 if (config != null) {
106 int x = config.MaxResponseHeadersLength;
110 defaultMaxResponseHeadersLength = x;
115 internal HttpWebRequest (Uri uri)
117 this.requestUri = uri;
118 this.actualUri = uri;
119 this.proxy = GlobalProxySelection.Select;
122 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
124 SerializationInfo info = serializationInfo;
126 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
127 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
128 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
129 allowBuffering = info.GetBoolean ("allowBuffering");
130 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
131 connectionGroup = info.GetString ("connectionGroup");
132 contentLength = info.GetInt64 ("contentLength");
133 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
134 keepAlive = info.GetBoolean ("keepAlive");
135 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
136 mediaType = info.GetString ("mediaType");
137 method = info.GetString ("method");
138 initialMethod = info.GetString ("initialMethod");
139 pipelined = info.GetBoolean ("pipelined");
140 version = (Version) info.GetValue ("version", typeof (Version));
141 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
142 sendChunked = info.GetBoolean ("sendChunked");
143 timeout = info.GetInt32 ("timeout");
144 redirects = info.GetInt32 ("redirects");
149 public string Accept {
150 get { return webHeaders ["Accept"]; }
152 CheckRequestStarted ();
153 webHeaders.RemoveAndAdd ("Accept", value);
158 get { return actualUri; }
161 public bool AllowAutoRedirect {
162 get { return allowAutoRedirect; }
163 set { this.allowAutoRedirect = value; }
166 public bool AllowWriteStreamBuffering {
167 get { return allowBuffering; }
168 set { allowBuffering = value; }
171 internal bool InternalAllowBuffering {
173 return (allowBuffering && (method != "HEAD" && method != "GET" &&
174 method != "MKCOL" && method != "CONNECT"));
178 public X509CertificateCollection ClientCertificates {
180 if (certificates == null)
181 certificates = new X509CertificateCollection ();
187 public string Connection {
188 get { return webHeaders ["Connection"]; }
190 CheckRequestStarted ();
193 val = val.Trim ().ToLower ();
195 if (val == null || val.Length == 0) {
196 webHeaders.RemoveInternal ("Connection");
200 if (val == "keep-alive" || val == "close")
201 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
203 if (keepAlive && val.IndexOf ("keep-alive") == -1)
204 value = value + ", Keep-Alive";
206 webHeaders.RemoveAndAdd ("Connection", value);
210 public override string ConnectionGroupName {
211 get { return connectionGroup; }
212 set { connectionGroup = value; }
215 public override long ContentLength {
216 get { return contentLength; }
218 CheckRequestStarted ();
220 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
222 contentLength = value;
226 internal long InternalContentLength {
227 set { contentLength = value; }
230 public override string ContentType {
231 get { return webHeaders ["Content-Type"]; }
233 if (value == null || value.Trim().Length == 0) {
234 webHeaders.RemoveInternal ("Content-Type");
237 webHeaders.RemoveAndAdd ("Content-Type", value);
241 public HttpContinueDelegate ContinueDelegate {
242 get { return continueDelegate; }
243 set { continueDelegate = value; }
246 public CookieContainer CookieContainer {
247 get { return cookieContainer; }
248 set { cookieContainer = value; }
251 public override ICredentials Credentials {
252 get { return credentials; }
253 set { credentials = value; }
256 public string Expect {
257 get { return webHeaders ["Expect"]; }
259 CheckRequestStarted ();
262 val = val.Trim ().ToLower ();
264 if (val == null || val.Length == 0) {
265 webHeaders.RemoveInternal ("Expect");
269 if (val == "100-continue")
270 throw new ArgumentException ("100-Continue cannot be set with this property.",
272 webHeaders.RemoveAndAdd ("Expect", value);
276 public bool HaveResponse {
277 get { return haveResponse; }
280 public override WebHeaderCollection Headers {
281 get { return webHeaders; }
283 CheckRequestStarted ();
284 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
285 int count = value.Count;
286 for (int i = 0; i < count; i++)
287 newHeaders.Add (value.GetKey (i), value.Get (i));
289 webHeaders = newHeaders;
293 public DateTime IfModifiedSince {
295 string str = webHeaders ["If-Modified-Since"];
299 return MonoHttpDate.Parse (str);
300 } catch (Exception) {
305 CheckRequestStarted ();
307 webHeaders.SetInternal ("If-Modified-Since",
308 value.ToUniversalTime ().ToString ("r", null));
309 // TODO: check last param when using different locale
313 public bool KeepAlive {
322 public int MaximumAutomaticRedirections {
323 get { return maxAutoRedirect; }
326 throw new ArgumentException ("Must be > 0", "value");
328 maxAutoRedirect = value;
333 [MonoTODO ("Use this")]
334 public int MaximumResponseHeadersLength {
335 get { return maxResponseHeadersLength; }
336 set { maxResponseHeadersLength = value; }
339 [MonoTODO ("Use this")]
340 public static int DefaultMaximumResponseHeadersLength {
341 get { return defaultMaxResponseHeadersLength; }
342 set { defaultMaxResponseHeadersLength = value; }
349 int ReadWriteTimeout {
350 get { return readWriteTimeout; }
353 throw new InvalidOperationException ("The request has already been sent.");
356 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
358 readWriteTimeout = value;
362 public string MediaType {
363 get { return mediaType; }
369 public override string Method {
370 get { return this.method; }
372 if (value == null || value.Trim () == "")
373 throw new ArgumentException ("not a valid method");
379 public bool Pipelined {
380 get { return pipelined; }
381 set { pipelined = value; }
384 public override bool PreAuthenticate {
385 get { return preAuthenticate; }
386 set { preAuthenticate = value; }
389 public Version ProtocolVersion {
390 get { return version; }
392 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
393 throw new ArgumentException ("value");
399 public override IWebProxy Proxy {
400 get { return proxy; }
402 CheckRequestStarted ();
404 throw new ArgumentNullException ("value");
407 servicePoint = null; // we may need a new one
411 public string Referer {
412 get { return webHeaders ["Referer"]; }
414 CheckRequestStarted ();
415 if (value == null || value.Trim().Length == 0) {
416 webHeaders.RemoveInternal ("Referer");
419 webHeaders.SetInternal ("Referer", value);
423 public override Uri RequestUri {
424 get { return requestUri; }
427 public bool SendChunked {
428 get { return sendChunked; }
430 CheckRequestStarted ();
435 public ServicePoint ServicePoint {
436 get { return GetServicePoint (); }
439 public override int Timeout {
440 get { return timeout; }
443 throw new ArgumentOutOfRangeException ("value");
449 public string TransferEncoding {
450 get { return webHeaders ["Transfer-Encoding"]; }
452 CheckRequestStarted ();
455 val = val.Trim ().ToLower ();
457 if (val == null || val.Length == 0) {
458 webHeaders.RemoveInternal ("Transfer-Encoding");
462 if (val == "chunked")
463 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
466 throw new ArgumentException ("SendChunked must be True", "value");
468 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
472 public string UserAgent {
473 get { return webHeaders ["User-Agent"]; }
474 set { webHeaders.SetInternal ("User-Agent", value); }
478 bool unsafe_auth_blah;
480 public bool UnsafeAuthenticatedConnectionSharing
482 get { return unsafe_auth_blah; }
483 set { unsafe_auth_blah = value; }
487 internal bool GotRequestStream {
488 get { return gotRequestStream; }
491 internal bool ExpectContinue {
492 get { return expectContinue; }
493 set { expectContinue = value; }
496 internal Uri AuthUri {
497 get { return actualUri; }
500 internal bool ProxyQuery {
501 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
506 internal ServicePoint GetServicePoint ()
509 if (hostChanged || servicePoint == null) {
510 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
518 public void AddRange (int range)
520 AddRange ("bytes", range);
523 public void AddRange (int from, int to)
525 AddRange ("bytes", from, to);
528 public void AddRange (string rangeSpecifier, int range)
530 if (rangeSpecifier == null)
531 throw new ArgumentNullException ("rangeSpecifier");
532 string value = webHeaders ["Range"];
533 if (value == null || value.Length == 0)
534 value = rangeSpecifier + "=";
535 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
538 throw new InvalidOperationException ("rangeSpecifier");
539 webHeaders.RemoveAndAdd ("Range", value + range + "-");
542 public void AddRange (string rangeSpecifier, int from, int to)
544 if (rangeSpecifier == null)
545 throw new ArgumentNullException ("rangeSpecifier");
546 if (from < 0 || to < 0 || from > to)
547 throw new ArgumentOutOfRangeException ();
548 string value = webHeaders ["Range"];
549 if (value == null || value.Length == 0)
550 value = rangeSpecifier + "=";
551 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
554 throw new InvalidOperationException ("rangeSpecifier");
555 webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
558 public override int GetHashCode ()
560 return base.GetHashCode ();
564 void CommonChecks (bool putpost)
567 throw new ProtocolViolationException ("Method is null.");
569 if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
570 throw new ProtocolViolationException ("Content-Length not set");
572 string transferEncoding = TransferEncoding;
573 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
574 throw new ProtocolViolationException ("SendChunked should be true.");
577 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
580 throw new WebException ("The request was previosly aborted.");
582 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD");
583 if (method == null || !send)
584 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
590 if (asyncWrite != null) {
591 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
592 "method while a previous call is still in progress.");
595 asyncWrite = new WebAsyncResult (this, callback, state);
596 initialMethod = method;
598 if (writeStream != null) {
599 asyncWrite.SetCompleted (true, writeStream);
600 asyncWrite.DoCallback ();
605 gotRequestStream = true;
606 WebAsyncResult result = asyncWrite;
610 servicePoint = GetServicePoint ();
611 abortHandler = servicePoint.SendRequest (this, connectionGroup);
617 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
619 if (asyncResult == null)
620 throw new ArgumentNullException ("asyncResult");
622 WebAsyncResult result = asyncResult as WebAsyncResult;
624 throw new ArgumentException ("Invalid IAsyncResult");
627 result.WaitUntilComplete ();
629 Exception e = result.Exception;
633 return result.WriteStream;
636 public override Stream GetRequestStream()
638 IAsyncResult asyncResult = BeginGetRequestStream (null, null);
639 asyncWrite = (WebAsyncResult) asyncResult;
640 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
642 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
645 return EndGetRequestStream (asyncResult);
648 void CheckIfForceWrite ()
650 if (writeStream == null || contentLength < 0 || !InternalAllowBuffering)
653 // This will write the POST/PUT if the write stream already has the expected
654 // amount of bytes in it (ContentLength) (bug #77753).
655 if (writeStream.WriteBufferLength == contentLength)
656 writeStream.WriteRequest ();
659 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
661 bool send = (method == "PUT" || method == "POST");
663 if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
664 throw new ProtocolViolationException ("Content-Length not set");
668 Monitor.Enter (this);
669 getResponseCalled = true;
670 if (asyncRead != null && !haveResponse) {
672 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
673 "method while a previous call is still in progress.");
676 CheckIfForceWrite ();
677 asyncRead = new WebAsyncResult (this, callback, state);
678 WebAsyncResult aread = asyncRead;
679 initialMethod = method;
681 if (webResponse != null) {
682 Exception saved = saved_exc;
685 aread.SetCompleted (true, webResponse);
687 aread.SetCompleted (true, saved);
697 servicePoint = GetServicePoint ();
698 abortHandler = servicePoint.SendRequest (this, connectionGroup);
705 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
707 if (asyncResult == null)
708 throw new ArgumentNullException ("asyncResult");
710 WebAsyncResult result = asyncResult as WebAsyncResult;
712 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
714 if (!result.WaitUntilComplete (timeout, false)) {
716 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
719 if (result.GotException)
720 throw result.Exception;
722 return result.Response;
725 public override WebResponse GetResponse()
727 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
728 return EndGetResponse (result);
731 public override void Abort ()
735 if (asyncWrite != null) {
736 WebAsyncResult r = asyncWrite;
737 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
738 r.SetCompleted (false, wexc);
743 if (asyncRead != null) {
744 WebAsyncResult r = asyncRead;
745 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
746 r.SetCompleted (false, wexc);
751 if (abortHandler != null) {
753 abortHandler (this, EventArgs.Empty);
754 } catch (Exception) {}
758 if (writeStream != null) {
760 writeStream.Close ();
765 if (webResponse != null) {
767 webResponse.Close ();
773 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
774 StreamingContext streamingContext)
776 SerializationInfo info = serializationInfo;
778 info.AddValue ("requestUri", requestUri, typeof (Uri));
779 info.AddValue ("actualUri", actualUri, typeof (Uri));
780 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
781 info.AddValue ("allowBuffering", allowBuffering);
782 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
783 info.AddValue ("connectionGroup", connectionGroup);
784 info.AddValue ("contentLength", contentLength);
785 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
786 info.AddValue ("keepAlive", keepAlive);
787 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
788 info.AddValue ("mediaType", mediaType);
789 info.AddValue ("method", method);
790 info.AddValue ("initialMethod", initialMethod);
791 info.AddValue ("pipelined", pipelined);
792 info.AddValue ("version", version, typeof (Version));
793 info.AddValue ("proxy", proxy, typeof (IWebProxy));
794 info.AddValue ("sendChunked", sendChunked);
795 info.AddValue ("timeout", timeout);
796 info.AddValue ("redirects", redirects);
799 void CheckRequestStarted ()
802 throw new InvalidOperationException ("request started");
805 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
807 if (continueDelegate != null)
808 continueDelegate (statusCode, headers);
811 bool Redirect (WebAsyncResult result, HttpStatusCode code)
815 string uriString = null;
818 case HttpStatusCode.Ambiguous: // 300
819 e = new WebException ("Ambiguous redirect.");
821 case HttpStatusCode.MovedPermanently: // 301
822 case HttpStatusCode.Redirect: // 302
823 case HttpStatusCode.TemporaryRedirect: // 307
824 /* MS follows the redirect for POST too
825 if (method != "GET" && method != "HEAD") // 10.3
829 uriString = webResponse.Headers ["Location"];
831 case HttpStatusCode.SeeOther: //303
833 uriString = webResponse.Headers ["Location"];
835 case HttpStatusCode.NotModified: // 304
837 case HttpStatusCode.UseProxy: // 305
838 e = new NotImplementedException ("Proxy support not available.");
840 case HttpStatusCode.Unused: // 306
842 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
849 if (uriString == null)
850 throw new WebException ("No Location header found for " + (int) code,
851 WebExceptionStatus.ProtocolError);
853 Uri prev = actualUri;
855 actualUri = new Uri (actualUri, uriString);
856 } catch (Exception) {
857 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
858 uriString, (int) code),
859 WebExceptionStatus.ProtocolError);
862 hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
863 actualUri.Port != prev.Port);
869 bool continue100 = false;
870 if (contentLength != -1) {
871 if (contentLength > 0)
873 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
874 webHeaders.RemoveInternal ("Transfer-Encoding");
875 } else if (sendChunked) {
877 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
878 webHeaders.RemoveInternal ("Content-Length");
881 if (actualVersion == HttpVersion.Version11 && continue100 &&
882 servicePoint.SendContinue) { // RFC2616 8.2.3
883 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
884 expectContinue = true;
886 webHeaders.RemoveInternal ("Expect");
887 expectContinue = false;
890 string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
891 webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
892 bool spoint10 = (servicePoint.ProtocolVersion == null ||
893 servicePoint.ProtocolVersion == HttpVersion.Version10);
895 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
896 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
897 } else if (!keepAlive && version == HttpVersion.Version11) {
898 webHeaders.RemoveAndAdd (connectionHeader, "close");
901 webHeaders.SetInternal ("Host", actualUri.Authority);
902 if (cookieContainer != null) {
903 string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
904 if (cookieHeader != "")
905 webHeaders.SetInternal ("Cookie", cookieHeader);
908 if (!usedPreAuth && preAuthenticate)
909 DoPreAuthenticate ();
911 return webHeaders.ToString ();
914 void DoPreAuthenticate ()
916 webHeaders.RemoveInternal ("Proxy-Authorization");
917 webHeaders.RemoveInternal ("Authorization");
918 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
919 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
920 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
924 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
925 webHeaders [authHeader] = auth.Message;
929 internal void SetWriteStreamError (WebExceptionStatus status)
934 WebAsyncResult r = asyncWrite;
939 r.SetCompleted (false, new WebException ("Error: " + status, status));
944 internal void SendRequestHeaders ()
946 StringBuilder req = new StringBuilder ();
949 query = actualUri.PathAndQuery;
950 } else if (actualUri.IsDefaultPort) {
951 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
953 actualUri.PathAndQuery);
955 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
958 actualUri.PathAndQuery);
961 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
962 actualVersion = servicePoint.ProtocolVersion;
964 actualVersion = version;
967 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
968 actualVersion.Major, actualVersion.Minor);
969 req.Append (GetHeaders ());
970 string reqstr = req.ToString ();
971 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
973 writeStream.SetHeaders (bytes, 0, bytes.Length);
974 } catch (WebException wexc) {
975 SetWriteStreamError (wexc.Status);
976 } catch (Exception) {
977 SetWriteStreamError (WebExceptionStatus.SendFailure);
981 internal void SetWriteStream (WebConnectionStream stream)
986 writeStream = stream;
987 if (bodyBuffer != null) {
988 webHeaders.RemoveInternal ("Transfer-Encoding");
989 contentLength = bodyBufferLength;
990 writeStream.SendChunked = false;
993 SendRequestHeaders ();
997 if (bodyBuffer != null) {
998 // The body has been written and buffered. The request "user"
999 // won't write it again, so we must do it.
1000 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1002 writeStream.Close ();
1003 } else if (method == "PUT" || method == "POST") {
1004 if (getResponseCalled && !writeStream.RequestWritten)
1005 writeStream.WriteRequest ();
1008 if (asyncWrite != null) {
1009 asyncWrite.SetCompleted (false, stream);
1010 asyncWrite.DoCallback ();
1015 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1019 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1020 WebAsyncResult r = asyncRead;
1026 if (e is WebException) {
1027 wexc = (WebException) e;
1029 wexc = new WebException (msg, e, status, null);
1031 r.SetCompleted (false, wexc);
1038 void CheckSendError (WebConnectionData data)
1040 // Got here, but no one called GetResponse
1041 int status = data.StatusCode;
1042 if (status < 400 || status == 401 || status == 407)
1045 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1046 // The request has not been completely sent and we got here!
1047 // We should probably just close and cause an error in any case,
1048 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1049 webResponse.ReadAll ();
1053 internal void SetResponseData (WebConnectionData data)
1056 if (data.stream != null)
1057 data.stream.Close ();
1061 WebException wexc = null;
1063 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1064 haveResponse = true;
1065 } catch (Exception e) {
1066 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1067 if (data.stream != null)
1068 data.stream.Close ();
1071 if (wexc == null && (method == "POST" || method == "PUT")) {
1073 CheckSendError (data);
1074 if (saved_exc != null)
1075 wexc = (WebException) saved_exc;
1079 WebAsyncResult r = asyncRead;
1082 r.SetCompleted (false, wexc);
1089 redirected = CheckFinalStatus (r);
1091 r.SetCompleted (false, webResponse);
1094 if (webResponse != null) {
1095 webResponse.Close ();
1098 haveResponse = false;
1101 servicePoint = GetServicePoint ();
1102 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1104 } catch (WebException wexc2) {
1105 r.SetCompleted (false, wexc2);
1108 } catch (Exception ex) {
1109 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1110 r.SetCompleted (false, wexc);
1117 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1119 authCompleted = false;
1120 if (code == HttpStatusCode.Unauthorized && credentials == null)
1123 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1124 if (isProxy && (proxy == null || proxy.Credentials == null))
1127 string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
1128 if (authHeader == null)
1131 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1132 Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1136 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1137 authCompleted = auth.Complete;
1141 // Returns true if redirected
1142 bool CheckFinalStatus (WebAsyncResult result)
1144 if (result.GotException)
1145 throw result.Exception;
1147 Exception throwMe = result.Exception;
1150 HttpWebResponse resp = result.Response;
1151 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1152 HttpStatusCode code = 0;
1153 if (throwMe == null && webResponse != null) {
1154 code = webResponse.StatusCode;
1155 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1156 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1157 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1158 // Keep the written body, so it can be rewritten in the retry
1159 if (InternalAllowBuffering) {
1160 bodyBuffer = writeStream.WriteBuffer;
1161 bodyBufferLength = writeStream.WriteBufferLength;
1162 webResponse.Close ();
1164 } else if (method != "PUT" && method != "POST") {
1165 webResponse.Close ();
1169 writeStream.InternalClose ();
1171 webResponse.Close ();
1174 throw new WebException ("This request requires buffering " +
1175 "of data for authentication or " +
1176 "redirection to be sucessful.");
1180 if ((int) code >= 400) {
1181 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1182 (int) code, webResponse.StatusDescription);
1183 throwMe = new WebException (err, null, protoError, webResponse);
1184 webResponse.ReadAll ();
1185 } else if ((int) code == 304 && allowAutoRedirect) {
1186 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1187 (int) code, webResponse.StatusDescription);
1188 throwMe = new WebException (err, null, protoError, webResponse);
1189 } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
1190 throwMe = new WebException ("Max. redirections exceeded.", null,
1191 protoError, webResponse);
1192 webResponse.ReadAll ();
1196 if (throwMe == null) {
1199 if (allowAutoRedirect && c >= 300) {
1200 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1201 bodyBuffer = writeStream.WriteBuffer;
1202 bodyBufferLength = writeStream.WriteBufferLength;
1204 b = Redirect (result, code);
1207 if (resp != null && c >= 300 && c != 304)
1213 if (writeStream != null) {
1214 writeStream.InternalClose ();