HttpWebRequest.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. //
  2. // System.Net.HttpWebRequest
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // (c) 2002 Lawrence Pit
  9. // (c) 2003 Ximian, Inc. (http://www.ximian.com)
  10. //
  11. using System;
  12. using System.Collections;
  13. using System.IO;
  14. using System.Net.Sockets;
  15. using System.Runtime.Remoting.Messaging;
  16. using System.Runtime.Serialization;
  17. using System.Security.Cryptography.X509Certificates;
  18. using System.Text;
  19. using System.Threading;
  20. namespace System.Net
  21. {
  22. [Serializable]
  23. public class HttpWebRequest : WebRequest, ISerializable
  24. {
  25. Uri requestUri;
  26. Uri actualUri;
  27. bool allowAutoRedirect = true;
  28. bool allowBuffering = true;
  29. X509CertificateCollection certificates;
  30. string connectionGroup;
  31. long contentLength = -1;
  32. HttpContinueDelegate continueDelegate;
  33. CookieContainer cookieContainer;
  34. ICredentials credentials;
  35. bool haveResponse;
  36. bool haveRequest;
  37. bool requestSent;
  38. WebHeaderCollection webHeaders = new WebHeaderCollection (true);
  39. bool keepAlive = true;
  40. int maxAutoRedirect = 50;
  41. string mediaType = String.Empty;
  42. string method = "GET";
  43. string initialMethod = "GET";
  44. bool pipelined = true;
  45. bool preAuthenticate;
  46. Version version = HttpVersion.Version11;
  47. IWebProxy proxy;
  48. bool sendChunked;
  49. ServicePoint servicePoint;
  50. int timeout = 100000;
  51. WebConnectionStream writeStream;
  52. HttpWebResponse webResponse;
  53. AutoResetEvent requestEndEvent;
  54. WebAsyncResult asyncWrite;
  55. WebAsyncResult asyncRead;
  56. EventHandler abortHandler;
  57. bool aborted;
  58. bool gotRequestStream;
  59. int redirects;
  60. // Constructors
  61. internal HttpWebRequest (Uri uri)
  62. {
  63. this.requestUri = uri;
  64. this.actualUri = uri;
  65. this.proxy = GlobalProxySelection.Select;
  66. }
  67. [MonoTODO]
  68. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  69. {
  70. throw new NotImplementedException ();
  71. }
  72. // Properties
  73. public string Accept {
  74. get { return webHeaders ["Accept"]; }
  75. set {
  76. CheckRequestStarted ();
  77. webHeaders.SetInternal ("Accept", value);
  78. }
  79. }
  80. public Uri Address {
  81. get { return actualUri; }
  82. }
  83. public bool AllowAutoRedirect {
  84. get { return allowAutoRedirect; }
  85. set { this.allowAutoRedirect = value; }
  86. }
  87. public bool AllowWriteStreamBuffering {
  88. get { return allowBuffering; }
  89. set { allowBuffering = value; }
  90. }
  91. internal bool InternalAllowBuffering {
  92. get {
  93. return (allowBuffering && (method == "PUT" || method == "POST"));
  94. }
  95. }
  96. public X509CertificateCollection ClientCertificates {
  97. get {
  98. if (certificates == null)
  99. certificates = new X509CertificateCollection ();
  100. return certificates;
  101. }
  102. }
  103. public string Connection {
  104. get { return webHeaders ["Connection"]; }
  105. set {
  106. CheckRequestStarted ();
  107. string val = value;
  108. if (val != null)
  109. val = val.Trim ().ToLower ();
  110. if (val == null || val.Length == 0) {
  111. webHeaders.RemoveInternal ("Connection");
  112. return;
  113. }
  114. if (val == "keep-alive" || val == "close")
  115. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  116. if (keepAlive && val.IndexOf ("keep-alive") == -1)
  117. value = value + ", Keep-Alive";
  118. webHeaders.SetInternal ("Connection", value);
  119. }
  120. }
  121. public override string ConnectionGroupName {
  122. get { return connectionGroup; }
  123. set { connectionGroup = value; }
  124. }
  125. public override long ContentLength {
  126. get { return contentLength; }
  127. set {
  128. CheckRequestStarted ();
  129. if (value < 0)
  130. throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
  131. contentLength = value;
  132. }
  133. }
  134. internal long InternalContentLength {
  135. set { contentLength = value; }
  136. }
  137. public override string ContentType {
  138. get { return webHeaders ["Content-Type"]; }
  139. set {
  140. CheckRequestStarted ();
  141. if (value == null || value.Trim().Length == 0) {
  142. webHeaders.RemoveInternal ("Content-Type");
  143. return;
  144. }
  145. webHeaders.SetInternal ("Content-Type", value);
  146. }
  147. }
  148. public HttpContinueDelegate ContinueDelegate {
  149. get { return continueDelegate; }
  150. set { continueDelegate = value; }
  151. }
  152. public CookieContainer CookieContainer {
  153. get { return cookieContainer; }
  154. set { cookieContainer = value; }
  155. }
  156. public override ICredentials Credentials {
  157. get { return credentials; }
  158. set { credentials = value; }
  159. }
  160. public string Expect {
  161. get { return webHeaders ["Expect"]; }
  162. set {
  163. CheckRequestStarted ();
  164. string val = value;
  165. if (val != null)
  166. val = val.Trim ().ToLower ();
  167. if (val == null || val.Length == 0) {
  168. webHeaders.RemoveInternal ("Expect");
  169. return;
  170. }
  171. if (val == "100-continue")
  172. throw new ArgumentException ("100-Continue cannot be set with this property.",
  173. "value");
  174. webHeaders.SetInternal ("Expect", value);
  175. }
  176. }
  177. public bool HaveResponse {
  178. get { return haveResponse; }
  179. }
  180. public override WebHeaderCollection Headers {
  181. get { return webHeaders; }
  182. set {
  183. CheckRequestStarted ();
  184. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  185. int count = value.Count;
  186. for (int i = 0; i < count; i++)
  187. newHeaders.Add (value.GetKey (i), value.Get (i));
  188. webHeaders = newHeaders;
  189. }
  190. }
  191. public DateTime IfModifiedSince {
  192. get {
  193. string str = webHeaders ["If-Modified-Since"];
  194. if (str == null)
  195. return DateTime.Now;
  196. try {
  197. return MonoHttpDate.Parse (str);
  198. } catch (Exception) {
  199. return DateTime.Now;
  200. }
  201. }
  202. set {
  203. CheckRequestStarted ();
  204. // rfc-1123 pattern
  205. webHeaders.SetInternal ("If-Modified-Since",
  206. value.ToUniversalTime ().ToString ("r", null));
  207. // TODO: check last param when using different locale
  208. }
  209. }
  210. public bool KeepAlive {
  211. get {
  212. return keepAlive;
  213. }
  214. set {
  215. keepAlive = value;
  216. }
  217. }
  218. public int MaximumAutomaticRedirections {
  219. get { return maxAutoRedirect; }
  220. set {
  221. if (value <= 0)
  222. throw new ArgumentException ("Must be > 0", "value");
  223. maxAutoRedirect = value;
  224. }
  225. }
  226. public string MediaType {
  227. get { return mediaType; }
  228. set {
  229. mediaType = value;
  230. }
  231. }
  232. public override string Method {
  233. get { return this.method; }
  234. set {
  235. if (value == null || value.Trim () == "")
  236. throw new ArgumentException ("not a valid method");
  237. method = value;
  238. }
  239. }
  240. public bool Pipelined {
  241. get { return pipelined; }
  242. set { pipelined = value; }
  243. }
  244. public override bool PreAuthenticate {
  245. get { return preAuthenticate; }
  246. set { preAuthenticate = value; }
  247. }
  248. public Version ProtocolVersion {
  249. get { return version; }
  250. set {
  251. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  252. throw new ArgumentException ("value");
  253. version = value;
  254. }
  255. }
  256. public override IWebProxy Proxy {
  257. get { return proxy; }
  258. set {
  259. CheckRequestStarted ();
  260. if (value == null)
  261. throw new ArgumentNullException ("value");
  262. proxy = value;
  263. }
  264. }
  265. public string Referer {
  266. get { return webHeaders ["Referer"]; }
  267. set {
  268. CheckRequestStarted ();
  269. if (value == null || value.Trim().Length == 0) {
  270. webHeaders.RemoveInternal ("Referer");
  271. return;
  272. }
  273. webHeaders.SetInternal ("Referer", value);
  274. }
  275. }
  276. public override Uri RequestUri {
  277. get { return requestUri; }
  278. }
  279. public bool SendChunked {
  280. get { return sendChunked; }
  281. set {
  282. CheckRequestStarted ();
  283. sendChunked = value;
  284. }
  285. }
  286. public ServicePoint ServicePoint {
  287. get { return GetServicePoint (); }
  288. }
  289. public override int Timeout {
  290. get { return timeout; }
  291. set {
  292. if (value < -1)
  293. throw new ArgumentOutOfRangeException ("value");
  294. timeout = value;
  295. }
  296. }
  297. public string TransferEncoding {
  298. get { return webHeaders ["Transfer-Encoding"]; }
  299. set {
  300. CheckRequestStarted ();
  301. string val = value;
  302. if (val != null)
  303. val = val.Trim ().ToLower ();
  304. if (val == null || val.Length == 0) {
  305. webHeaders.RemoveInternal ("Transfer-Encoding");
  306. return;
  307. }
  308. if (val == "chunked")
  309. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  310. if (!sendChunked)
  311. throw new ArgumentException ("SendChunked must be True", "value");
  312. webHeaders.SetInternal ("Transfer-Encoding", value);
  313. }
  314. }
  315. public string UserAgent {
  316. get { return webHeaders ["User-Agent"]; }
  317. set { webHeaders.SetInternal ("User-Agent", value); }
  318. }
  319. internal bool GotRequestStream {
  320. get { return gotRequestStream; }
  321. }
  322. // Methods
  323. internal ServicePoint GetServicePoint ()
  324. {
  325. if (servicePoint != null)
  326. return servicePoint;
  327. lock (this) {
  328. if (servicePoint == null)
  329. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  330. }
  331. return servicePoint;
  332. }
  333. public void AddRange (int range)
  334. {
  335. AddRange ("bytes", range);
  336. }
  337. public void AddRange (int from, int to)
  338. {
  339. AddRange ("bytes", from, to);
  340. }
  341. public void AddRange (string rangeSpecifier, int range)
  342. {
  343. if (rangeSpecifier == null)
  344. throw new ArgumentNullException ("rangeSpecifier");
  345. string value = webHeaders ["Range"];
  346. if (value == null || value.Length == 0)
  347. value = rangeSpecifier + "=";
  348. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  349. value += ",";
  350. else
  351. throw new InvalidOperationException ("rangeSpecifier");
  352. webHeaders.SetInternal ("Range", value + range + "-");
  353. }
  354. public void AddRange (string rangeSpecifier, int from, int to)
  355. {
  356. if (rangeSpecifier == null)
  357. throw new ArgumentNullException ("rangeSpecifier");
  358. if (from < 0 || to < 0 || from > to)
  359. throw new ArgumentOutOfRangeException ();
  360. string value = webHeaders ["Range"];
  361. if (value == null || value.Length == 0)
  362. value = rangeSpecifier + "=";
  363. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  364. value += ",";
  365. else
  366. throw new InvalidOperationException ("rangeSpecifier");
  367. webHeaders.SetInternal ("Range", value + from + "-" + to);
  368. }
  369. public override int GetHashCode ()
  370. {
  371. return base.GetHashCode ();
  372. }
  373. void CommonChecks (bool putpost)
  374. {
  375. if (method == null)
  376. throw new ProtocolViolationException ("Method is null.");
  377. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  378. throw new ProtocolViolationException ("Content-Length not set");
  379. string transferEncoding = TransferEncoding;
  380. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  381. throw new ProtocolViolationException ("SendChunked should be true.");
  382. }
  383. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  384. {
  385. if (aborted)
  386. throw new WebException ("The request was previosly aborted.");
  387. bool send = (method == "PUT" || method == "POST");
  388. if (method == null || !send)
  389. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  390. CommonChecks (send);
  391. Monitor.Enter (this);
  392. if (asyncWrite != null) {
  393. Monitor.Exit (this);
  394. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  395. "method while a previous call is still in progress.");
  396. }
  397. WebAsyncResult result;
  398. result = asyncWrite = new WebAsyncResult (this, callback, state);
  399. initialMethod = method;
  400. if (haveRequest) {
  401. if (writeStream != null) {
  402. Monitor.Exit (this);
  403. result.SetCompleted (true, writeStream);
  404. result.DoCallback ();
  405. return result;
  406. }
  407. }
  408. haveRequest = true;
  409. gotRequestStream = true;
  410. Monitor.Exit (this);
  411. servicePoint = GetServicePoint ();
  412. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  413. return result;
  414. }
  415. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  416. {
  417. if (asyncResult == null)
  418. throw new ArgumentNullException ("asyncResult");
  419. WebAsyncResult result = asyncResult as WebAsyncResult;
  420. if (result == null)
  421. throw new ArgumentException ("Invalid IAsyncResult");
  422. result.WaitUntilComplete ();
  423. Exception e = result.Exception;
  424. if (e != null)
  425. throw e;
  426. return result.WriteStream;
  427. }
  428. public override Stream GetRequestStream()
  429. {
  430. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  431. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  432. Abort ();
  433. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  434. }
  435. return EndGetRequestStream (asyncResult);
  436. }
  437. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  438. {
  439. bool send = (method == "PUT" || method == "POST");
  440. if (send) {
  441. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  442. throw new ProtocolViolationException ("Content-Length not set");
  443. }
  444. CommonChecks (send);
  445. Monitor.Enter (this);
  446. if (asyncRead != null && !haveResponse) {
  447. Monitor.Exit (this);
  448. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  449. "method while a previous call is still in progress.");
  450. }
  451. asyncRead = new WebAsyncResult (this, callback, state);
  452. initialMethod = method;
  453. if (haveResponse) {
  454. if (webResponse != null) {
  455. Monitor.Exit (this);
  456. asyncRead.SetCompleted (true, webResponse);
  457. asyncRead.DoCallback ();
  458. return asyncRead;
  459. }
  460. }
  461. if (!requestSent) {
  462. servicePoint = GetServicePoint ();
  463. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  464. }
  465. Monitor.Exit (this);
  466. return asyncRead;
  467. }
  468. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  469. {
  470. if (asyncResult == null)
  471. throw new ArgumentNullException ("asyncResult");
  472. WebAsyncResult result = asyncResult as WebAsyncResult;
  473. if (result == null)
  474. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  475. redirects = 0;
  476. bool redirected = false;
  477. asyncRead = result;
  478. do {
  479. if (redirected) {
  480. haveResponse = false;
  481. result.Reset ();
  482. servicePoint = GetServicePoint ();
  483. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  484. }
  485. if (!result.WaitUntilComplete (timeout, false)) {
  486. Abort ();
  487. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  488. }
  489. redirected = CheckFinalStatus (result);
  490. } while (redirected);
  491. return result.Response;
  492. }
  493. public override WebResponse GetResponse()
  494. {
  495. if (haveResponse && webResponse != null)
  496. return webResponse;
  497. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  498. return EndGetResponse (result);
  499. }
  500. public override void Abort ()
  501. {
  502. haveResponse = true;
  503. aborted = true;
  504. asyncRead = null;
  505. asyncWrite = null;
  506. if (abortHandler != null) {
  507. try {
  508. abortHandler (this, EventArgs.Empty);
  509. } catch {}
  510. abortHandler = null;
  511. }
  512. if (writeStream != null) {
  513. try {
  514. writeStream.Close ();
  515. writeStream = null;
  516. } catch {}
  517. }
  518. if (webResponse != null) {
  519. try {
  520. webResponse.Close ();
  521. webResponse = null;
  522. } catch {}
  523. }
  524. }
  525. [MonoTODO]
  526. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  527. StreamingContext streamingContext)
  528. {
  529. throw new NotImplementedException ();
  530. }
  531. void CheckRequestStarted ()
  532. {
  533. if (haveRequest)
  534. throw new InvalidOperationException ("request started");
  535. }
  536. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  537. {
  538. if (continueDelegate != null)
  539. continueDelegate (statusCode, headers);
  540. }
  541. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  542. {
  543. redirects++;
  544. Exception e = null;
  545. string uriString = null;
  546. switch (code) {
  547. case HttpStatusCode.Ambiguous: // 300
  548. e = new WebException ("Ambiguous redirect.");
  549. break;
  550. case HttpStatusCode.MovedPermanently: // 301
  551. case HttpStatusCode.Redirect: // 302
  552. case HttpStatusCode.TemporaryRedirect: // 307
  553. if (method != "GET" && method != "HEAD") // 10.3
  554. return false;
  555. uriString = webResponse.Headers ["Location"];
  556. break;
  557. case HttpStatusCode.SeeOther: //303
  558. method = "GET";
  559. uriString = webResponse.Headers ["Location"];
  560. break;
  561. case HttpStatusCode.NotModified: // 304
  562. return false;
  563. case HttpStatusCode.UseProxy: // 305
  564. e = new NotImplementedException ("Proxy support not available.");
  565. break;
  566. case HttpStatusCode.Unused: // 306
  567. default:
  568. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  569. break;
  570. }
  571. if (e != null)
  572. throw e;
  573. actualUri = new Uri (uriString);
  574. return true;
  575. }
  576. string GetHeaders ()
  577. {
  578. StringBuilder result = new StringBuilder ();
  579. bool continue100 = false;
  580. if (gotRequestStream && contentLength != -1) {
  581. continue100 = true;
  582. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  583. } else if (sendChunked) {
  584. continue100 = true;
  585. webHeaders.SetInternal ("Transfer-Encoding", "chunked");
  586. }
  587. if (continue100) // RFC2616 8.2.3
  588. webHeaders.SetInternal ("Expect" , "100-continue");
  589. if (keepAlive && version == HttpVersion.Version10)
  590. webHeaders.SetInternal ("Connection", "keep-alive");
  591. else if (!keepAlive && version == HttpVersion.Version11)
  592. webHeaders.SetInternal ("Connection", "close");
  593. webHeaders.SetInternal ("Host", actualUri.Host);
  594. if (cookieContainer != null) {
  595. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  596. if (cookieHeader != "")
  597. webHeaders.SetInternal ("Cookie", cookieHeader);
  598. }
  599. return webHeaders.ToString ();
  600. }
  601. internal void SetWriteStreamError (WebExceptionStatus status)
  602. {
  603. if (aborted) {
  604. //TODO
  605. }
  606. WebAsyncResult r = asyncWrite;
  607. if (r == null)
  608. r = asyncRead;
  609. if (r != null) {
  610. r.SetCompleted (false, new WebException ("Error: " + status, status));
  611. r.DoCallback ();
  612. }
  613. }
  614. internal void SendRequestHeaders ()
  615. {
  616. StringBuilder req = new StringBuilder ();
  617. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, actualUri.PathAndQuery,
  618. version.Major, version.Minor);
  619. req.Append (GetHeaders ());
  620. string reqstr = req.ToString ();
  621. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  622. writeStream.SetHeaders (bytes, 0, bytes.Length);
  623. }
  624. internal void SetWriteStream (WebConnectionStream stream)
  625. {
  626. if (aborted) {
  627. //TODO
  628. }
  629. writeStream = stream;
  630. haveRequest = true;
  631. if (asyncWrite != null) {
  632. asyncWrite.SetCompleted (false, stream);
  633. asyncWrite.DoCallback ();
  634. asyncWrite = null;
  635. }
  636. SendRequestHeaders ();
  637. }
  638. internal void SetResponseError (WebExceptionStatus status, Exception e)
  639. {
  640. WebAsyncResult r = asyncRead;
  641. if (r == null)
  642. r = asyncWrite;
  643. if (r != null) {
  644. WebException wexc = new WebException ("Error getting response stream", e, status, null);
  645. r.SetCompleted (false, wexc);
  646. r.DoCallback ();
  647. }
  648. }
  649. internal void SetResponseData (WebConnectionData data)
  650. {
  651. if (aborted) {
  652. if (data.stream != null)
  653. data.stream.Close ();
  654. return;
  655. }
  656. webResponse = new HttpWebResponse (actualUri, method, data);
  657. haveResponse = true;
  658. if (asyncRead != null) {
  659. asyncRead.SetCompleted (false, webResponse);
  660. asyncRead.DoCallback ();
  661. }
  662. }
  663. // Returns true if redirected
  664. bool CheckFinalStatus (WebAsyncResult result)
  665. {
  666. Exception throwMe = result.Exception;
  667. HttpWebResponse resp = result.Response;
  668. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  669. HttpStatusCode code = 0;
  670. if (throwMe == null && webResponse != null) {
  671. code = webResponse.StatusCode;
  672. if ((int) code >= 400 ) {
  673. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  674. (int) code, webResponse.StatusDescription);
  675. throwMe = new WebException (err, null, protoError, webResponse);
  676. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  677. throwMe = new WebException ("Max. redirections exceeded.", null,
  678. protoError, webResponse);
  679. }
  680. }
  681. if (throwMe == null) {
  682. bool b = false;
  683. if (allowAutoRedirect && (int) code >= 300)
  684. b = Redirect (result, code);
  685. return b;
  686. }
  687. if (writeStream != null) {
  688. writeStream.Close ();
  689. writeStream = null;
  690. }
  691. if (webResponse != null)
  692. webResponse = null;
  693. throw throwMe;
  694. }
  695. }
  696. }