WebClient.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. //
  2. // System.Net.WebClient
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Atsushi Enomoto ([email protected])
  8. // Miguel de Icaza ([email protected])
  9. //
  10. // Copyright 2003 Ximian, Inc. (http://www.ximian.com)
  11. // Copyright 2006, 2010 Novell, Inc. (http://www.novell.com)
  12. //
  13. //
  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:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  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.
  32. //
  33. //
  34. // Notes on CancelAsync and Async methods:
  35. //
  36. // WebClient.CancelAsync is implemented by calling Thread.Interrupt
  37. // in our helper thread. The various async methods have to cancel
  38. // any ongoing requests by calling request.Abort () at that point.
  39. // In a few places (UploadDataCore, UploadValuesCore,
  40. // UploadFileCore) we catch the ThreadInterruptedException and
  41. // abort the request there.
  42. //
  43. // Higher level routines (the async callbacks) also need to catch
  44. // the exception and raise the OnXXXXCompleted events there with
  45. // the "canceled" flag set to true.
  46. //
  47. // In a few other places where these helper routines are not used
  48. // (OpenReadAsync for example) catching the ThreadAbortException
  49. // also must abort the request.
  50. //
  51. // The Async methods currently differ in their implementation from
  52. // the .NET implementation in that we manually catch any other
  53. // exceptions and correctly raise the OnXXXXCompleted passing the
  54. // Exception that caused the problem. The .NET implementation
  55. // does not seem to have a mechanism to flag errors that happen
  56. // during downloads though. We do this because we still need to
  57. // catch the exception on these helper threads, or we would
  58. // otherwise kill the application (on the 2.x profile, uncaught
  59. // exceptions in threads terminate the application).
  60. //
  61. using System;
  62. using System.Collections.Specialized;
  63. using System.ComponentModel;
  64. using System.IO;
  65. using System.Runtime.InteropServices;
  66. using System.Runtime.Serialization;
  67. using System.Text;
  68. using System.Threading;
  69. using System.Net.Cache;
  70. namespace System.Net
  71. {
  72. [ComVisible(true)]
  73. public class WebClient : Component
  74. {
  75. static readonly string urlEncodedCType = "application/x-www-form-urlencoded";
  76. static byte [] hexBytes;
  77. ICredentials credentials;
  78. WebHeaderCollection headers;
  79. WebHeaderCollection responseHeaders;
  80. Uri baseAddress;
  81. string baseString;
  82. NameValueCollection queryString;
  83. bool is_busy;
  84. bool async;
  85. Thread async_thread;
  86. Encoding encoding = Encoding.Default;
  87. IWebProxy proxy;
  88. // RequestCachePolicy cache_policy;
  89. // Constructors
  90. static WebClient ()
  91. {
  92. hexBytes = new byte [16];
  93. int index = 0;
  94. for (int i = '0'; i <= '9'; i++, index++)
  95. hexBytes [index] = (byte) i;
  96. for (int i = 'a'; i <= 'f'; i++, index++)
  97. hexBytes [index] = (byte) i;
  98. }
  99. public WebClient ()
  100. {
  101. }
  102. // Properties
  103. public string BaseAddress {
  104. get {
  105. if (baseString == null) {
  106. if (baseAddress == null)
  107. return string.Empty;
  108. }
  109. baseString = baseAddress.ToString ();
  110. return baseString;
  111. }
  112. set {
  113. if (value == null || value.Length == 0) {
  114. baseAddress = null;
  115. } else {
  116. baseAddress = new Uri (value);
  117. }
  118. }
  119. }
  120. static Exception GetMustImplement ()
  121. {
  122. return new NotImplementedException ();
  123. }
  124. [MonoTODO ("Value can be set but is currently ignored")]
  125. public RequestCachePolicy CachePolicy
  126. {
  127. get {
  128. throw GetMustImplement ();
  129. }
  130. set { /*cache_policy = value;*/ }
  131. }
  132. [MonoTODO ("Value can be set but is ignored")]
  133. public bool UseDefaultCredentials
  134. {
  135. get {
  136. throw GetMustImplement ();
  137. }
  138. set {
  139. // This makes no sense in mono
  140. }
  141. }
  142. public ICredentials Credentials {
  143. get { return credentials; }
  144. set { credentials = value; }
  145. }
  146. public WebHeaderCollection Headers {
  147. get {
  148. if (headers == null)
  149. headers = new WebHeaderCollection ();
  150. return headers;
  151. }
  152. set { headers = value; }
  153. }
  154. public NameValueCollection QueryString {
  155. get {
  156. if (queryString == null)
  157. queryString = new NameValueCollection ();
  158. return queryString;
  159. }
  160. set { queryString = value; }
  161. }
  162. public WebHeaderCollection ResponseHeaders {
  163. get { return responseHeaders; }
  164. }
  165. public Encoding Encoding {
  166. get { return encoding; }
  167. set {
  168. if (value == null)
  169. throw new ArgumentNullException ("Encoding");
  170. encoding = value;
  171. }
  172. }
  173. public IWebProxy Proxy {
  174. get { return proxy; }
  175. set { proxy = value; }
  176. }
  177. public bool IsBusy {
  178. get { return is_busy; }
  179. }
  180. // Methods
  181. void CheckBusy ()
  182. {
  183. if (IsBusy)
  184. throw new NotSupportedException ("WebClient does not support conccurent I/O operations.");
  185. }
  186. void SetBusy ()
  187. {
  188. lock (this) {
  189. CheckBusy ();
  190. is_busy = true;
  191. }
  192. }
  193. // DownloadData
  194. public byte [] DownloadData (string address)
  195. {
  196. if (address == null)
  197. throw new ArgumentNullException ("address");
  198. return DownloadData (CreateUri (address));
  199. }
  200. public byte [] DownloadData (Uri address)
  201. {
  202. if (address == null)
  203. throw new ArgumentNullException ("address");
  204. try {
  205. SetBusy ();
  206. async = false;
  207. return DownloadDataCore (address, null);
  208. } finally {
  209. is_busy = false;
  210. }
  211. }
  212. byte [] DownloadDataCore (Uri address, object userToken)
  213. {
  214. WebRequest request = null;
  215. try {
  216. request = SetupRequest (address);
  217. return ReadAll (request, userToken);
  218. } catch (ThreadInterruptedException){
  219. if (request != null)
  220. request.Abort ();
  221. throw;
  222. } catch (WebException) {
  223. throw;
  224. } catch (Exception ex) {
  225. throw new WebException ("An error occurred " +
  226. "performing a WebClient request.", ex);
  227. }
  228. }
  229. // DownloadFile
  230. public void DownloadFile (string address, string fileName)
  231. {
  232. if (address == null)
  233. throw new ArgumentNullException ("address");
  234. DownloadFile (CreateUri (address), fileName);
  235. }
  236. public void DownloadFile (Uri address, string fileName)
  237. {
  238. if (address == null)
  239. throw new ArgumentNullException ("address");
  240. if (fileName == null)
  241. throw new ArgumentNullException ("fileName");
  242. try {
  243. SetBusy ();
  244. async = false;
  245. DownloadFileCore (address, fileName, null);
  246. } catch (WebException) {
  247. throw;
  248. } catch (Exception ex) {
  249. throw new WebException ("An error occurred " +
  250. "performing a WebClient request.", ex);
  251. } finally {
  252. is_busy = false;
  253. }
  254. }
  255. void DownloadFileCore (Uri address, string fileName, object userToken)
  256. {
  257. WebRequest request = null;
  258. using (FileStream f = new FileStream (fileName, FileMode.Create)) {
  259. try {
  260. request = SetupRequest (address);
  261. WebResponse response = GetWebResponse (request);
  262. Stream st = response.GetResponseStream ();
  263. int cLength = (int) response.ContentLength;
  264. int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
  265. byte [] buffer = new byte [length];
  266. int nread = 0;
  267. long notify_total = 0;
  268. while ((nread = st.Read (buffer, 0, length)) != 0){
  269. if (async){
  270. notify_total += nread;
  271. OnDownloadProgressChanged (
  272. new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
  273. }
  274. f.Write (buffer, 0, nread);
  275. }
  276. } catch (ThreadInterruptedException){
  277. if (request != null)
  278. request.Abort ();
  279. throw;
  280. }
  281. }
  282. }
  283. // OpenRead
  284. public Stream OpenRead (string address)
  285. {
  286. if (address == null)
  287. throw new ArgumentNullException ("address");
  288. return OpenRead (CreateUri (address));
  289. }
  290. public Stream OpenRead (Uri address)
  291. {
  292. if (address == null)
  293. throw new ArgumentNullException ("address");
  294. WebRequest request = null;
  295. try {
  296. SetBusy ();
  297. async = false;
  298. request = SetupRequest (address);
  299. WebResponse response = GetWebResponse (request);
  300. return response.GetResponseStream ();
  301. } catch (WebException) {
  302. throw;
  303. } catch (Exception ex) {
  304. throw new WebException ("An error occurred " +
  305. "performing a WebClient request.", ex);
  306. } finally {
  307. is_busy = false;
  308. }
  309. }
  310. // OpenWrite
  311. public Stream OpenWrite (string address)
  312. {
  313. if (address == null)
  314. throw new ArgumentNullException ("address");
  315. return OpenWrite (CreateUri (address));
  316. }
  317. public Stream OpenWrite (string address, string method)
  318. {
  319. if (address == null)
  320. throw new ArgumentNullException ("address");
  321. return OpenWrite (CreateUri (address), method);
  322. }
  323. public Stream OpenWrite (Uri address)
  324. {
  325. return OpenWrite (address, (string) null);
  326. }
  327. public Stream OpenWrite (Uri address, string method)
  328. {
  329. if (address == null)
  330. throw new ArgumentNullException ("address");
  331. try {
  332. SetBusy ();
  333. async = false;
  334. WebRequest request = SetupRequest (address, method, true);
  335. return request.GetRequestStream ();
  336. } catch (WebException) {
  337. throw;
  338. } catch (Exception ex) {
  339. throw new WebException ("An error occurred " +
  340. "performing a WebClient request.", ex);
  341. } finally {
  342. is_busy = false;
  343. }
  344. }
  345. private string DetermineMethod (Uri address, string method, bool is_upload)
  346. {
  347. if (method != null)
  348. return method;
  349. if (address.Scheme == Uri.UriSchemeFtp)
  350. return (is_upload) ? "STOR" : "RETR";
  351. return (is_upload) ? "POST" : "GET";
  352. }
  353. // UploadData
  354. public byte [] UploadData (string address, byte [] data)
  355. {
  356. if (address == null)
  357. throw new ArgumentNullException ("address");
  358. return UploadData (CreateUri (address), data);
  359. }
  360. public byte [] UploadData (string address, string method, byte [] data)
  361. {
  362. if (address == null)
  363. throw new ArgumentNullException ("address");
  364. return UploadData (CreateUri (address), method, data);
  365. }
  366. public byte [] UploadData (Uri address, byte [] data)
  367. {
  368. return UploadData (address, (string) null, data);
  369. }
  370. public byte [] UploadData (Uri address, string method, byte [] data)
  371. {
  372. if (address == null)
  373. throw new ArgumentNullException ("address");
  374. if (data == null)
  375. throw new ArgumentNullException ("data");
  376. try {
  377. SetBusy ();
  378. async = false;
  379. return UploadDataCore (address, method, data, null);
  380. } catch (WebException) {
  381. throw;
  382. } catch (Exception ex) {
  383. throw new WebException ("An error occurred " +
  384. "performing a WebClient request.", ex);
  385. } finally {
  386. is_busy = false;
  387. }
  388. }
  389. byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
  390. {
  391. WebRequest request = SetupRequest (address, method, true);
  392. try {
  393. int contentLength = data.Length;
  394. request.ContentLength = contentLength;
  395. using (Stream stream = request.GetRequestStream ()) {
  396. stream.Write (data, 0, contentLength);
  397. }
  398. return ReadAll (request, userToken);
  399. } catch (ThreadInterruptedException){
  400. if (request != null)
  401. request.Abort ();
  402. throw;
  403. }
  404. }
  405. // UploadFile
  406. public byte [] UploadFile (string address, string fileName)
  407. {
  408. if (address == null)
  409. throw new ArgumentNullException ("address");
  410. return UploadFile (CreateUri (address), fileName);
  411. }
  412. public byte [] UploadFile (Uri address, string fileName)
  413. {
  414. return UploadFile (address, (string) null, fileName);
  415. }
  416. public byte [] UploadFile (string address, string method, string fileName)
  417. {
  418. return UploadFile (CreateUri (address), method, fileName);
  419. }
  420. public byte [] UploadFile (Uri address, string method, string fileName)
  421. {
  422. if (address == null)
  423. throw new ArgumentNullException ("address");
  424. if (fileName == null)
  425. throw new ArgumentNullException ("fileName");
  426. try {
  427. SetBusy ();
  428. async = false;
  429. return UploadFileCore (address, method, fileName, null);
  430. } catch (WebException) {
  431. throw;
  432. } catch (Exception ex) {
  433. throw new WebException ("An error occurred " +
  434. "performing a WebClient request.", ex);
  435. } finally {
  436. is_busy = false;
  437. }
  438. }
  439. byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
  440. {
  441. string fileCType = Headers ["Content-Type"];
  442. if (fileCType != null) {
  443. string lower = fileCType.ToLower ();
  444. if (lower.StartsWith ("multipart/"))
  445. throw new WebException ("Content-Type cannot be set to a multipart" +
  446. " type for this request.");
  447. } else {
  448. fileCType = "application/octet-stream";
  449. }
  450. string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
  451. Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
  452. Stream reqStream = null;
  453. Stream fStream = null;
  454. byte [] resultBytes = null;
  455. fileName = Path.GetFullPath (fileName);
  456. WebRequest request = null;
  457. try {
  458. fStream = File.OpenRead (fileName);
  459. request = SetupRequest (address, method, true);
  460. reqStream = request.GetRequestStream ();
  461. byte [] bytes_boundary = Encoding.ASCII.GetBytes (boundary);
  462. reqStream.WriteByte ((byte) '-');
  463. reqStream.WriteByte ((byte) '-');
  464. reqStream.Write (bytes_boundary, 0, bytes_boundary.Length);
  465. reqStream.WriteByte ((byte) '\r');
  466. reqStream.WriteByte ((byte) '\n');
  467. string partHeaders = String.Format ("Content-Disposition: form-data; " +
  468. "name=\"file\"; filename=\"{0}\"\r\n" +
  469. "Content-Type: {1}\r\n\r\n",
  470. Path.GetFileName (fileName), fileCType);
  471. byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
  472. reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
  473. int nread;
  474. byte [] buffer = new byte [4096];
  475. while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
  476. reqStream.Write (buffer, 0, nread);
  477. reqStream.WriteByte ((byte) '\r');
  478. reqStream.WriteByte ((byte) '\n');
  479. reqStream.WriteByte ((byte) '-');
  480. reqStream.WriteByte ((byte) '-');
  481. reqStream.Write (bytes_boundary, 0, bytes_boundary.Length);
  482. reqStream.WriteByte ((byte) '-');
  483. reqStream.WriteByte ((byte) '-');
  484. reqStream.WriteByte ((byte) '\r');
  485. reqStream.WriteByte ((byte) '\n');
  486. reqStream.Close ();
  487. reqStream = null;
  488. resultBytes = ReadAll (request, userToken);
  489. } catch (ThreadInterruptedException){
  490. if (request != null)
  491. request.Abort ();
  492. throw;
  493. } finally {
  494. if (fStream != null)
  495. fStream.Close ();
  496. if (reqStream != null)
  497. reqStream.Close ();
  498. }
  499. return resultBytes;
  500. }
  501. public byte[] UploadValues (string address, NameValueCollection data)
  502. {
  503. if (address == null)
  504. throw new ArgumentNullException ("address");
  505. return UploadValues (CreateUri (address), data);
  506. }
  507. public byte[] UploadValues (string address, string method, NameValueCollection data)
  508. {
  509. if (address == null)
  510. throw new ArgumentNullException ("address");
  511. return UploadValues (CreateUri (address), method, data);
  512. }
  513. public byte[] UploadValues (Uri address, NameValueCollection data)
  514. {
  515. return UploadValues (address, (string) null, data);
  516. }
  517. public byte[] UploadValues (Uri address, string method, NameValueCollection data)
  518. {
  519. if (address == null)
  520. throw new ArgumentNullException ("address");
  521. if (data == null)
  522. throw new ArgumentNullException ("data");
  523. try {
  524. SetBusy ();
  525. async = false;
  526. return UploadValuesCore (address, method, data, null);
  527. } catch (WebException) {
  528. throw;
  529. } catch (Exception ex) {
  530. throw new WebException ("An error occurred " +
  531. "performing a WebClient request.", ex);
  532. } finally {
  533. is_busy = false;
  534. }
  535. }
  536. byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
  537. {
  538. string cType = Headers ["Content-Type"];
  539. if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
  540. throw new WebException ("Content-Type header cannot be changed from its default " +
  541. "value for this request.");
  542. Headers ["Content-Type"] = urlEncodedCType;
  543. WebRequest request = SetupRequest (uri, method, true);
  544. try {
  545. MemoryStream tmpStream = new MemoryStream ();
  546. foreach (string key in data) {
  547. byte [] bytes = Encoding.UTF8.GetBytes (key);
  548. UrlEncodeAndWrite (tmpStream, bytes);
  549. tmpStream.WriteByte ((byte) '=');
  550. bytes = Encoding.UTF8.GetBytes (data [key]);
  551. UrlEncodeAndWrite (tmpStream, bytes);
  552. tmpStream.WriteByte ((byte) '&');
  553. }
  554. int length = (int) tmpStream.Length;
  555. if (length > 0)
  556. tmpStream.SetLength (--length); // remove trailing '&'
  557. byte [] buf = tmpStream.GetBuffer ();
  558. request.ContentLength = length;
  559. using (Stream rqStream = request.GetRequestStream ()) {
  560. rqStream.Write (buf, 0, length);
  561. }
  562. tmpStream.Close ();
  563. return ReadAll (request, userToken);
  564. } catch (ThreadInterruptedException) {
  565. request.Abort ();
  566. throw;
  567. }
  568. }
  569. public string DownloadString (string address)
  570. {
  571. if (address == null)
  572. throw new ArgumentNullException ("address");
  573. return encoding.GetString (DownloadData (CreateUri (address)));
  574. }
  575. public string DownloadString (Uri address)
  576. {
  577. if (address == null)
  578. throw new ArgumentNullException ("address");
  579. return encoding.GetString (DownloadData (CreateUri (address)));
  580. }
  581. public string UploadString (string address, string data)
  582. {
  583. if (address == null)
  584. throw new ArgumentNullException ("address");
  585. if (data == null)
  586. throw new ArgumentNullException ("data");
  587. byte [] resp = UploadData (address, encoding.GetBytes (data));
  588. return encoding.GetString (resp);
  589. }
  590. public string UploadString (string address, string method, string data)
  591. {
  592. if (address == null)
  593. throw new ArgumentNullException ("address");
  594. if (data == null)
  595. throw new ArgumentNullException ("data");
  596. byte [] resp = UploadData (address, method, encoding.GetBytes (data));
  597. return encoding.GetString (resp);
  598. }
  599. public string UploadString (Uri address, string data)
  600. {
  601. if (address == null)
  602. throw new ArgumentNullException ("address");
  603. if (data == null)
  604. throw new ArgumentNullException ("data");
  605. byte [] resp = UploadData (address, encoding.GetBytes (data));
  606. return encoding.GetString (resp);
  607. }
  608. public string UploadString (Uri address, string method, string data)
  609. {
  610. if (address == null)
  611. throw new ArgumentNullException ("address");
  612. if (data == null)
  613. throw new ArgumentNullException ("data");
  614. byte [] resp = UploadData (address, method, encoding.GetBytes (data));
  615. return encoding.GetString (resp);
  616. }
  617. public event DownloadDataCompletedEventHandler DownloadDataCompleted;
  618. public event AsyncCompletedEventHandler DownloadFileCompleted;
  619. public event DownloadProgressChangedEventHandler DownloadProgressChanged;
  620. public event DownloadStringCompletedEventHandler DownloadStringCompleted;
  621. public event OpenReadCompletedEventHandler OpenReadCompleted;
  622. public event OpenWriteCompletedEventHandler OpenWriteCompleted;
  623. public event UploadDataCompletedEventHandler UploadDataCompleted;
  624. public event UploadFileCompletedEventHandler UploadFileCompleted;
  625. public event UploadProgressChangedEventHandler UploadProgressChanged;
  626. public event UploadStringCompletedEventHandler UploadStringCompleted;
  627. public event UploadValuesCompletedEventHandler UploadValuesCompleted;
  628. Uri CreateUri (string address)
  629. {
  630. Uri uri;
  631. try {
  632. if (baseAddress == null)
  633. uri = new Uri (address);
  634. else
  635. uri = new Uri (baseAddress, address);
  636. return CreateUri (uri);
  637. } catch {
  638. }
  639. return new Uri (Path.GetFullPath (address));
  640. }
  641. Uri CreateUri (Uri address)
  642. {
  643. Uri result = address;
  644. if (baseAddress != null && !result.IsAbsoluteUri) {
  645. try {
  646. result = new Uri (baseAddress, result.OriginalString);
  647. } catch {
  648. return result; // Not much we can do here.
  649. }
  650. }
  651. string query = result.Query;
  652. if (String.IsNullOrEmpty (query))
  653. query = GetQueryString (true);
  654. UriBuilder builder = new UriBuilder (address);
  655. if (!String.IsNullOrEmpty (query))
  656. builder.Query = query.Substring (1);
  657. return builder.Uri;
  658. }
  659. string GetQueryString (bool add_qmark)
  660. {
  661. if (queryString == null || queryString.Count == 0)
  662. return null;
  663. StringBuilder sb = new StringBuilder ();
  664. if (add_qmark)
  665. sb.Append ('?');
  666. foreach (string key in queryString)
  667. sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
  668. if (sb.Length != 0)
  669. sb.Length--; // removes last '&' or the '?' if empty.
  670. if (sb.Length == 0)
  671. return null;
  672. return sb.ToString ();
  673. }
  674. WebRequest SetupRequest (Uri uri)
  675. {
  676. WebRequest request = GetWebRequest (uri);
  677. if (Proxy != null)
  678. request.Proxy = Proxy;
  679. if (credentials != null)
  680. request.Credentials = credentials;
  681. // Special headers. These are properties of HttpWebRequest.
  682. // What do we do with other requests differnt from HttpWebRequest?
  683. if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
  684. HttpWebRequest req = (HttpWebRequest) request;
  685. string expect = headers ["Expect"];
  686. string contentType = headers ["Content-Type"];
  687. string accept = headers ["Accept"];
  688. string connection = headers ["Connection"];
  689. string userAgent = headers ["User-Agent"];
  690. string referer = headers ["Referer"];
  691. headers.RemoveInternal ("Expect");
  692. headers.RemoveInternal ("Content-Type");
  693. headers.RemoveInternal ("Accept");
  694. headers.RemoveInternal ("Connection");
  695. headers.RemoveInternal ("Referer");
  696. headers.RemoveInternal ("User-Agent");
  697. request.Headers = headers;
  698. if (expect != null && expect.Length > 0)
  699. req.Expect = expect;
  700. if (accept != null && accept.Length > 0)
  701. req.Accept = accept;
  702. if (contentType != null && contentType.Length > 0)
  703. req.ContentType = contentType;
  704. if (connection != null && connection.Length > 0)
  705. req.Connection = connection;
  706. if (userAgent != null && userAgent.Length > 0)
  707. req.UserAgent = userAgent;
  708. if (referer != null && referer.Length > 0)
  709. req.Referer = referer;
  710. }
  711. responseHeaders = null;
  712. return request;
  713. }
  714. WebRequest SetupRequest (Uri uri, string method, bool is_upload)
  715. {
  716. WebRequest request = SetupRequest (uri);
  717. request.Method = DetermineMethod (uri, method, is_upload);
  718. return request;
  719. }
  720. byte [] ReadAll (WebRequest request, object userToken)
  721. {
  722. WebResponse response = GetWebResponse (request);
  723. Stream stream = response.GetResponseStream ();
  724. int length = (int) response.ContentLength;
  725. HttpWebRequest wreq = request as HttpWebRequest;
  726. if (length > -1 && wreq != null && (int) wreq.AutomaticDecompression != 0) {
  727. string content_encoding = ((HttpWebResponse) response).ContentEncoding;
  728. if (((content_encoding == "gzip" && (wreq.AutomaticDecompression & DecompressionMethods.GZip) != 0)) ||
  729. ((content_encoding == "deflate" && (wreq.AutomaticDecompression & DecompressionMethods.Deflate) != 0)))
  730. length = -1;
  731. }
  732. MemoryStream ms = null;
  733. bool nolength = (length == -1);
  734. int size = ((nolength) ? 8192 : length);
  735. if (nolength)
  736. ms = new MemoryStream ();
  737. // long total = 0;
  738. int nread = 0;
  739. int offset = 0;
  740. byte [] buffer = new byte [size];
  741. while ((nread = stream.Read (buffer, offset, size)) != 0) {
  742. if (nolength) {
  743. ms.Write (buffer, 0, nread);
  744. } else {
  745. offset += nread;
  746. size -= nread;
  747. }
  748. if (async){
  749. // total += nread;
  750. OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
  751. }
  752. }
  753. if (nolength)
  754. return ms.ToArray ();
  755. return buffer;
  756. }
  757. string UrlEncode (string str)
  758. {
  759. StringBuilder result = new StringBuilder ();
  760. int len = str.Length;
  761. for (int i = 0; i < len; i++) {
  762. char c = str [i];
  763. if (c == ' ')
  764. result.Append ('+');
  765. else if ((c < '0' && c != '-' && c != '.') ||
  766. (c < 'A' && c > '9') ||
  767. (c > 'Z' && c < 'a' && c != '_') ||
  768. (c > 'z')) {
  769. result.Append ('%');
  770. int idx = ((int) c) >> 4;
  771. result.Append ((char) hexBytes [idx]);
  772. idx = ((int) c) & 0x0F;
  773. result.Append ((char) hexBytes [idx]);
  774. } else {
  775. result.Append (c);
  776. }
  777. }
  778. return result.ToString ();
  779. }
  780. static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
  781. {
  782. if (bytes == null)
  783. return;
  784. int len = bytes.Length;
  785. if (len == 0)
  786. return;
  787. for (int i = 0; i < len; i++) {
  788. char c = (char) bytes [i];
  789. if (c == ' ')
  790. stream.WriteByte ((byte) '+');
  791. else if ((c < '0' && c != '-' && c != '.') ||
  792. (c < 'A' && c > '9') ||
  793. (c > 'Z' && c < 'a' && c != '_') ||
  794. (c > 'z')) {
  795. stream.WriteByte ((byte) '%');
  796. int idx = ((int) c) >> 4;
  797. stream.WriteByte (hexBytes [idx]);
  798. idx = ((int) c) & 0x0F;
  799. stream.WriteByte (hexBytes [idx]);
  800. } else {
  801. stream.WriteByte ((byte) c);
  802. }
  803. }
  804. }
  805. public void CancelAsync ()
  806. {
  807. lock (this){
  808. if (async_thread == null)
  809. return;
  810. //
  811. // We first flag things as done, in case the Interrupt hangs
  812. // or the thread decides to hang in some other way inside the
  813. // event handlers, or if we are stuck somewhere else. This
  814. // ensures that the WebClient object is reusable immediately
  815. //
  816. Thread t = async_thread;
  817. CompleteAsync ();
  818. t.Interrupt ();
  819. }
  820. }
  821. void CompleteAsync ()
  822. {
  823. lock (this){
  824. is_busy = false;
  825. async_thread = null;
  826. }
  827. }
  828. // DownloadDataAsync
  829. public void DownloadDataAsync (Uri address)
  830. {
  831. DownloadDataAsync (address, null);
  832. }
  833. public void DownloadDataAsync (Uri address, object userToken)
  834. {
  835. if (address == null)
  836. throw new ArgumentNullException ("address");
  837. lock (this) {
  838. SetBusy ();
  839. async = true;
  840. async_thread = new Thread (delegate (object state) {
  841. object [] args = (object []) state;
  842. try {
  843. byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
  844. OnDownloadDataCompleted (
  845. new DownloadDataCompletedEventArgs (data, null, false, args [1]));
  846. } catch (ThreadInterruptedException){
  847. OnDownloadDataCompleted (
  848. new DownloadDataCompletedEventArgs (null, null, true, args [1]));
  849. throw;
  850. } catch (Exception e){
  851. OnDownloadDataCompleted (
  852. new DownloadDataCompletedEventArgs (null, e, false, args [1]));
  853. }
  854. });
  855. object [] cb_args = new object [] {address, userToken};
  856. async_thread.Start (cb_args);
  857. }
  858. }
  859. // DownloadFileAsync
  860. public void DownloadFileAsync (Uri address, string fileName)
  861. {
  862. DownloadFileAsync (address, fileName, null);
  863. }
  864. public void DownloadFileAsync (Uri address, string fileName, object userToken)
  865. {
  866. if (address == null)
  867. throw new ArgumentNullException ("address");
  868. if (fileName == null)
  869. throw new ArgumentNullException ("fileName");
  870. lock (this) {
  871. SetBusy ();
  872. async = true;
  873. async_thread = new Thread (delegate (object state) {
  874. object [] args = (object []) state;
  875. try {
  876. DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
  877. OnDownloadFileCompleted (
  878. new AsyncCompletedEventArgs (null, false, args [2]));
  879. } catch (ThreadInterruptedException){
  880. OnDownloadFileCompleted (
  881. new AsyncCompletedEventArgs (null, true, args [2]));
  882. } catch (Exception e){
  883. OnDownloadFileCompleted (
  884. new AsyncCompletedEventArgs (e, false, args [2]));
  885. }});
  886. object [] cb_args = new object [] {address, fileName, userToken};
  887. async_thread.Start (cb_args);
  888. }
  889. }
  890. // DownloadStringAsync
  891. public void DownloadStringAsync (Uri address)
  892. {
  893. DownloadStringAsync (address, null);
  894. }
  895. public void DownloadStringAsync (Uri address, object userToken)
  896. {
  897. if (address == null)
  898. throw new ArgumentNullException ("address");
  899. lock (this) {
  900. SetBusy ();
  901. async = true;
  902. async_thread = new Thread (delegate (object state) {
  903. object [] args = (object []) state;
  904. try {
  905. string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
  906. OnDownloadStringCompleted (
  907. new DownloadStringCompletedEventArgs (data, null, false, args [1]));
  908. } catch (ThreadInterruptedException){
  909. OnDownloadStringCompleted (
  910. new DownloadStringCompletedEventArgs (null, null, true, args [1]));
  911. } catch (Exception e){
  912. OnDownloadStringCompleted (
  913. new DownloadStringCompletedEventArgs (null, e, false, args [1]));
  914. }});
  915. object [] cb_args = new object [] {address, userToken};
  916. async_thread.Start (cb_args);
  917. }
  918. }
  919. // OpenReadAsync
  920. public void OpenReadAsync (Uri address)
  921. {
  922. OpenReadAsync (address, null);
  923. }
  924. public void OpenReadAsync (Uri address, object userToken)
  925. {
  926. if (address == null)
  927. throw new ArgumentNullException ("address");
  928. lock (this) {
  929. SetBusy ();
  930. async = true;
  931. async_thread = new Thread (delegate (object state) {
  932. object [] args = (object []) state;
  933. WebRequest request = null;
  934. try {
  935. request = SetupRequest ((Uri) args [0]);
  936. WebResponse response = GetWebResponse (request);
  937. Stream stream = response.GetResponseStream ();
  938. OnOpenReadCompleted (
  939. new OpenReadCompletedEventArgs (stream, null, false, args [1]));
  940. } catch (ThreadInterruptedException){
  941. if (request != null)
  942. request.Abort ();
  943. OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
  944. } catch (Exception e){
  945. OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
  946. } });
  947. object [] cb_args = new object [] {address, userToken};
  948. async_thread.Start (cb_args);
  949. }
  950. }
  951. // OpenWriteAsync
  952. public void OpenWriteAsync (Uri address)
  953. {
  954. OpenWriteAsync (address, null);
  955. }
  956. public void OpenWriteAsync (Uri address, string method)
  957. {
  958. OpenWriteAsync (address, method, null);
  959. }
  960. public void OpenWriteAsync (Uri address, string method, object userToken)
  961. {
  962. if (address == null)
  963. throw new ArgumentNullException ("address");
  964. lock (this) {
  965. SetBusy ();
  966. async = true;
  967. async_thread = new Thread (delegate (object state) {
  968. object [] args = (object []) state;
  969. WebRequest request = null;
  970. try {
  971. request = SetupRequest ((Uri) args [0], (string) args [1], true);
  972. Stream stream = request.GetRequestStream ();
  973. OnOpenWriteCompleted (
  974. new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
  975. } catch (ThreadInterruptedException){
  976. if (request != null)
  977. request.Abort ();
  978. OnOpenWriteCompleted (
  979. new OpenWriteCompletedEventArgs (null, null, true, args [2]));
  980. } catch (Exception e){
  981. OnOpenWriteCompleted (
  982. new OpenWriteCompletedEventArgs (null, e, false, args [2]));
  983. }});
  984. object [] cb_args = new object [] {address, method, userToken};
  985. async_thread.Start (cb_args);
  986. }
  987. }
  988. // UploadDataAsync
  989. public void UploadDataAsync (Uri address, byte [] data)
  990. {
  991. UploadDataAsync (address, null, data);
  992. }
  993. public void UploadDataAsync (Uri address, string method, byte [] data)
  994. {
  995. UploadDataAsync (address, method, data, null);
  996. }
  997. public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
  998. {
  999. if (address == null)
  1000. throw new ArgumentNullException ("address");
  1001. if (data == null)
  1002. throw new ArgumentNullException ("data");
  1003. lock (this) {
  1004. SetBusy ();
  1005. async = true;
  1006. async_thread = new Thread (delegate (object state) {
  1007. object [] args = (object []) state;
  1008. byte [] data2;
  1009. try {
  1010. data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
  1011. OnUploadDataCompleted (
  1012. new UploadDataCompletedEventArgs (data2, null, false, args [3]));
  1013. } catch (ThreadInterruptedException){
  1014. OnUploadDataCompleted (
  1015. new UploadDataCompletedEventArgs (null, null, true, args [3]));
  1016. } catch (Exception e){
  1017. OnUploadDataCompleted (
  1018. new UploadDataCompletedEventArgs (null, e, false, args [3]));
  1019. }});
  1020. object [] cb_args = new object [] {address, method, data, userToken};
  1021. async_thread.Start (cb_args);
  1022. }
  1023. }
  1024. // UploadFileAsync
  1025. public void UploadFileAsync (Uri address, string fileName)
  1026. {
  1027. UploadFileAsync (address, null, fileName);
  1028. }
  1029. public void UploadFileAsync (Uri address, string method, string fileName)
  1030. {
  1031. UploadFileAsync (address, method, fileName, null);
  1032. }
  1033. public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
  1034. {
  1035. if (address == null)
  1036. throw new ArgumentNullException ("address");
  1037. if (fileName == null)
  1038. throw new ArgumentNullException ("fileName");
  1039. lock (this) {
  1040. SetBusy ();
  1041. async = true;
  1042. async_thread = new Thread (delegate (object state) {
  1043. object [] args = (object []) state;
  1044. byte [] data;
  1045. try {
  1046. data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
  1047. OnUploadFileCompleted (
  1048. new UploadFileCompletedEventArgs (data, null, false, args [3]));
  1049. } catch (ThreadInterruptedException){
  1050. OnUploadFileCompleted (
  1051. new UploadFileCompletedEventArgs (null, null, true, args [3]));
  1052. } catch (Exception e){
  1053. OnUploadFileCompleted (
  1054. new UploadFileCompletedEventArgs (null, e, false, args [3]));
  1055. }});
  1056. object [] cb_args = new object [] {address, method, fileName, userToken};
  1057. async_thread.Start (cb_args);
  1058. }
  1059. }
  1060. // UploadStringAsync
  1061. public void UploadStringAsync (Uri address, string data)
  1062. {
  1063. UploadStringAsync (address, null, data);
  1064. }
  1065. public void UploadStringAsync (Uri address, string method, string data)
  1066. {
  1067. UploadStringAsync (address, method, data, null);
  1068. }
  1069. public void UploadStringAsync (Uri address, string method, string data, object userToken)
  1070. {
  1071. if (address == null)
  1072. throw new ArgumentNullException ("address");
  1073. if (data == null)
  1074. throw new ArgumentNullException ("data");
  1075. lock (this) {
  1076. CheckBusy ();
  1077. async = true;
  1078. async_thread = new Thread (delegate (object state) {
  1079. object [] args = (object []) state;
  1080. try {
  1081. string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
  1082. OnUploadStringCompleted (
  1083. new UploadStringCompletedEventArgs (data2, null, false, args [3]));
  1084. } catch (ThreadInterruptedException){
  1085. OnUploadStringCompleted (
  1086. new UploadStringCompletedEventArgs (null, null, true, args [3]));
  1087. } catch (Exception e){
  1088. OnUploadStringCompleted (
  1089. new UploadStringCompletedEventArgs (null, e, false, args [3]));
  1090. }});
  1091. object [] cb_args = new object [] {address, method, data, userToken};
  1092. async_thread.Start (cb_args);
  1093. }
  1094. }
  1095. // UploadValuesAsync
  1096. public void UploadValuesAsync (Uri address, NameValueCollection values)
  1097. {
  1098. UploadValuesAsync (address, null, values);
  1099. }
  1100. public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
  1101. {
  1102. UploadValuesAsync (address, method, values, null);
  1103. }
  1104. public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
  1105. {
  1106. if (address == null)
  1107. throw new ArgumentNullException ("address");
  1108. if (values == null)
  1109. throw new ArgumentNullException ("values");
  1110. lock (this) {
  1111. CheckBusy ();
  1112. async = true;
  1113. async_thread = new Thread (delegate (object state) {
  1114. object [] args = (object []) state;
  1115. try {
  1116. byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
  1117. OnUploadValuesCompleted (
  1118. new UploadValuesCompletedEventArgs (data, null, false, args [3]));
  1119. } catch (ThreadInterruptedException){
  1120. OnUploadValuesCompleted (
  1121. new UploadValuesCompletedEventArgs (null, null, true, args [3]));
  1122. } catch (Exception e){
  1123. OnUploadValuesCompleted (
  1124. new UploadValuesCompletedEventArgs (null, e, false, args [3]));
  1125. }});
  1126. object [] cb_args = new object [] {address, method, values, userToken};
  1127. async_thread.Start (cb_args);
  1128. }
  1129. }
  1130. protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
  1131. {
  1132. CompleteAsync ();
  1133. if (DownloadDataCompleted != null)
  1134. DownloadDataCompleted (this, args);
  1135. }
  1136. protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
  1137. {
  1138. CompleteAsync ();
  1139. if (DownloadFileCompleted != null)
  1140. DownloadFileCompleted (this, args);
  1141. }
  1142. protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
  1143. {
  1144. if (DownloadProgressChanged != null)
  1145. DownloadProgressChanged (this, e);
  1146. }
  1147. protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
  1148. {
  1149. CompleteAsync ();
  1150. if (DownloadStringCompleted != null)
  1151. DownloadStringCompleted (this, args);
  1152. }
  1153. protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
  1154. {
  1155. CompleteAsync ();
  1156. if (OpenReadCompleted != null)
  1157. OpenReadCompleted (this, args);
  1158. }
  1159. protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
  1160. {
  1161. CompleteAsync ();
  1162. if (OpenWriteCompleted != null)
  1163. OpenWriteCompleted (this, args);
  1164. }
  1165. protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
  1166. {
  1167. CompleteAsync ();
  1168. if (UploadDataCompleted != null)
  1169. UploadDataCompleted (this, args);
  1170. }
  1171. protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
  1172. {
  1173. CompleteAsync ();
  1174. if (UploadFileCompleted != null)
  1175. UploadFileCompleted (this, args);
  1176. }
  1177. protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
  1178. {
  1179. if (UploadProgressChanged != null)
  1180. UploadProgressChanged (this, e);
  1181. }
  1182. protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
  1183. {
  1184. CompleteAsync ();
  1185. if (UploadStringCompleted != null)
  1186. UploadStringCompleted (this, args);
  1187. }
  1188. protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
  1189. {
  1190. CompleteAsync ();
  1191. if (UploadValuesCompleted != null)
  1192. UploadValuesCompleted (this, args);
  1193. }
  1194. protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
  1195. {
  1196. WebResponse response = request.EndGetResponse (result);
  1197. responseHeaders = response.Headers;
  1198. return response;
  1199. }
  1200. protected virtual WebRequest GetWebRequest (Uri address)
  1201. {
  1202. return WebRequest.Create (address);
  1203. }
  1204. protected virtual WebResponse GetWebResponse (WebRequest request)
  1205. {
  1206. WebResponse response = request.GetResponse ();
  1207. responseHeaders = response.Headers;
  1208. return response;
  1209. }
  1210. }
  1211. }