2
0

HttpWebRequest.cs 20 KB

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