2 // System.Net.WebClient
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Atsushi Enomoto (atsushi@ximian.com)
8 // Miguel de Icaza (miguel@ximian.com)
10 // Copyright 2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright 2006, 2010 Novell, Inc. (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 // Notes on CancelAsync and Async methods:
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.
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.
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.
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).
62 using System.Collections.Specialized;
63 using System.ComponentModel;
65 using System.Runtime.InteropServices;
66 using System.Runtime.Serialization;
68 using System.Threading;
69 using System.Net.Cache;
74 public class WebClient : Component
76 static readonly string urlEncodedCType = "application/x-www-form-urlencoded";
77 static byte [] hexBytes;
78 ICredentials credentials;
79 WebHeaderCollection headers;
80 WebHeaderCollection responseHeaders;
83 NameValueCollection queryString;
86 bool proxySet = false;
88 Encoding encoding = Encoding.Default;
90 // RequestCachePolicy cache_policy;
95 hexBytes = new byte [16];
97 for (int i = '0'; i <= '9'; i++, index++)
98 hexBytes [index] = (byte) i;
100 for (int i = 'a'; i <= 'f'; i++, index++)
101 hexBytes [index] = (byte) i;
110 public string BaseAddress {
112 if (baseString == null) {
113 if (baseAddress == null)
117 baseString = baseAddress.ToString ();
122 if (value == null || value.Length == 0) {
125 baseAddress = new Uri (value);
130 static Exception GetMustImplement ()
132 return new NotImplementedException ();
135 [MonoTODO ("Value can be set but is currently ignored")]
136 public RequestCachePolicy CachePolicy
139 throw GetMustImplement ();
141 set { /*cache_policy = value;*/ }
144 [MonoTODO ("Value can be set but is ignored")]
145 public bool UseDefaultCredentials
148 throw GetMustImplement ();
151 // This makes no sense in mono
155 public ICredentials Credentials {
156 get { return credentials; }
157 set { credentials = value; }
160 public WebHeaderCollection Headers {
163 headers = new WebHeaderCollection ();
167 set { headers = value; }
170 public NameValueCollection QueryString {
172 if (queryString == null)
173 queryString = new NameValueCollection ();
177 set { queryString = value; }
180 public WebHeaderCollection ResponseHeaders {
181 get { return responseHeaders; }
184 public Encoding Encoding {
185 get { return encoding; }
188 throw new ArgumentNullException ("Encoding");
193 public IWebProxy Proxy {
196 return WebRequest.DefaultWebProxy;
207 get { return is_busy; }
214 throw new NotSupportedException ("WebClient does not support conccurent I/O operations.");
227 public byte [] DownloadData (string address)
230 throw new ArgumentNullException ("address");
232 return DownloadData (CreateUri (address));
235 public byte [] DownloadData (Uri address)
238 throw new ArgumentNullException ("address");
243 return DownloadDataCore (address, null);
249 byte [] DownloadDataCore (Uri address, object userToken)
251 WebRequest request = null;
254 request = SetupRequest (address);
255 return ReadAll (request, userToken);
256 } catch (ThreadInterruptedException){
260 } catch (WebException) {
262 } catch (Exception ex) {
263 throw new WebException ("An error occurred " +
264 "performing a WebClient request.", ex);
270 public void DownloadFile (string address, string fileName)
273 throw new ArgumentNullException ("address");
275 DownloadFile (CreateUri (address), fileName);
278 public void DownloadFile (Uri address, string fileName)
281 throw new ArgumentNullException ("address");
282 if (fileName == null)
283 throw new ArgumentNullException ("fileName");
288 DownloadFileCore (address, fileName, null);
289 } catch (WebException) {
291 } catch (Exception ex) {
292 throw new WebException ("An error occurred " +
293 "performing a WebClient request.", ex);
299 void DownloadFileCore (Uri address, string fileName, object userToken)
301 WebRequest request = null;
303 using (FileStream f = new FileStream (fileName, FileMode.Create)) {
305 request = SetupRequest (address);
306 WebResponse response = GetWebResponse (request);
307 Stream st = response.GetResponseStream ();
309 int cLength = (int) response.ContentLength;
310 int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
311 byte [] buffer = new byte [length];
314 long notify_total = 0;
315 while ((nread = st.Read (buffer, 0, length)) != 0){
317 notify_total += nread;
318 OnDownloadProgressChanged (
319 new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
322 f.Write (buffer, 0, nread);
324 } catch (ThreadInterruptedException){
334 public Stream OpenRead (string address)
337 throw new ArgumentNullException ("address");
338 return OpenRead (CreateUri (address));
341 public Stream OpenRead (Uri address)
344 throw new ArgumentNullException ("address");
346 WebRequest request = null;
350 request = SetupRequest (address);
351 WebResponse response = GetWebResponse (request);
352 return response.GetResponseStream ();
353 } catch (WebException) {
355 } catch (Exception ex) {
356 throw new WebException ("An error occurred " +
357 "performing a WebClient request.", ex);
365 public Stream OpenWrite (string address)
368 throw new ArgumentNullException ("address");
370 return OpenWrite (CreateUri (address));
373 public Stream OpenWrite (string address, string method)
376 throw new ArgumentNullException ("address");
378 return OpenWrite (CreateUri (address), method);
381 public Stream OpenWrite (Uri address)
383 return OpenWrite (address, (string) null);
386 public Stream OpenWrite (Uri address, string method)
389 throw new ArgumentNullException ("address");
394 WebRequest request = SetupRequest (address, method, true);
395 return request.GetRequestStream ();
396 } catch (WebException) {
398 } catch (Exception ex) {
399 throw new WebException ("An error occurred " +
400 "performing a WebClient request.", ex);
406 private string DetermineMethod (Uri address, string method, bool is_upload)
411 if (address.Scheme == Uri.UriSchemeFtp)
412 return (is_upload) ? "STOR" : "RETR";
414 return (is_upload) ? "POST" : "GET";
419 public byte [] UploadData (string address, byte [] data)
422 throw new ArgumentNullException ("address");
424 return UploadData (CreateUri (address), data);
427 public byte [] UploadData (string address, string method, byte [] data)
430 throw new ArgumentNullException ("address");
432 return UploadData (CreateUri (address), method, data);
435 public byte [] UploadData (Uri address, byte [] data)
437 return UploadData (address, (string) null, data);
440 public byte [] UploadData (Uri address, string method, byte [] data)
443 throw new ArgumentNullException ("address");
445 throw new ArgumentNullException ("data");
450 return UploadDataCore (address, method, data, null);
451 } catch (WebException) {
453 } catch (Exception ex) {
454 throw new WebException ("An error occurred " +
455 "performing a WebClient request.", ex);
461 byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
463 WebRequest request = SetupRequest (address, method, true);
465 int contentLength = data.Length;
466 request.ContentLength = contentLength;
467 using (Stream stream = request.GetRequestStream ()) {
468 stream.Write (data, 0, contentLength);
471 return ReadAll (request, userToken);
472 } catch (ThreadInterruptedException){
481 public byte [] UploadFile (string address, string fileName)
484 throw new ArgumentNullException ("address");
486 return UploadFile (CreateUri (address), fileName);
489 public byte [] UploadFile (Uri address, string fileName)
491 return UploadFile (address, (string) null, fileName);
494 public byte [] UploadFile (string address, string method, string fileName)
496 return UploadFile (CreateUri (address), method, fileName);
499 public byte [] UploadFile (Uri address, string method, string fileName)
502 throw new ArgumentNullException ("address");
503 if (fileName == null)
504 throw new ArgumentNullException ("fileName");
509 return UploadFileCore (address, method, fileName, null);
510 } catch (WebException) {
512 } catch (Exception ex) {
513 throw new WebException ("An error occurred " +
514 "performing a WebClient request.", ex);
520 byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
522 string fileCType = Headers ["Content-Type"];
523 if (fileCType != null) {
524 string lower = fileCType.ToLower ();
525 if (lower.StartsWith ("multipart/"))
526 throw new WebException ("Content-Type cannot be set to a multipart" +
527 " type for this request.");
529 fileCType = "application/octet-stream";
532 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
533 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
534 Stream reqStream = null;
535 Stream fStream = null;
536 byte [] resultBytes = null;
538 fileName = Path.GetFullPath (fileName);
540 WebRequest request = null;
542 fStream = File.OpenRead (fileName);
543 request = SetupRequest (address, method, true);
544 reqStream = request.GetRequestStream ();
545 byte [] bytes_boundary = Encoding.ASCII.GetBytes (boundary);
546 reqStream.WriteByte ((byte) '-');
547 reqStream.WriteByte ((byte) '-');
548 reqStream.Write (bytes_boundary, 0, bytes_boundary.Length);
549 reqStream.WriteByte ((byte) '\r');
550 reqStream.WriteByte ((byte) '\n');
551 string partHeaders = String.Format ("Content-Disposition: form-data; " +
552 "name=\"file\"; filename=\"{0}\"\r\n" +
553 "Content-Type: {1}\r\n\r\n",
554 Path.GetFileName (fileName), fileCType);
556 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
557 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
559 byte [] buffer = new byte [4096];
560 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
561 reqStream.Write (buffer, 0, nread);
563 reqStream.WriteByte ((byte) '\r');
564 reqStream.WriteByte ((byte) '\n');
565 reqStream.WriteByte ((byte) '-');
566 reqStream.WriteByte ((byte) '-');
567 reqStream.Write (bytes_boundary, 0, bytes_boundary.Length);
568 reqStream.WriteByte ((byte) '-');
569 reqStream.WriteByte ((byte) '-');
570 reqStream.WriteByte ((byte) '\r');
571 reqStream.WriteByte ((byte) '\n');
574 resultBytes = ReadAll (request, userToken);
575 } catch (ThreadInterruptedException){
583 if (reqStream != null)
590 public byte[] UploadValues (string address, NameValueCollection data)
593 throw new ArgumentNullException ("address");
595 return UploadValues (CreateUri (address), data);
598 public byte[] UploadValues (string address, string method, NameValueCollection data)
601 throw new ArgumentNullException ("address");
602 return UploadValues (CreateUri (address), method, data);
605 public byte[] UploadValues (Uri address, NameValueCollection data)
607 return UploadValues (address, (string) null, data);
610 public byte[] UploadValues (Uri address, string method, NameValueCollection data)
613 throw new ArgumentNullException ("address");
615 throw new ArgumentNullException ("data");
620 return UploadValuesCore (address, method, data, null);
621 } catch (WebException) {
623 } catch (Exception ex) {
624 throw new WebException ("An error occurred " +
625 "performing a WebClient request.", ex);
631 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
633 string cType = Headers ["Content-Type"];
634 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
635 throw new WebException ("Content-Type header cannot be changed from its default " +
636 "value for this request.");
638 Headers ["Content-Type"] = urlEncodedCType;
639 WebRequest request = SetupRequest (uri, method, true);
641 MemoryStream tmpStream = new MemoryStream ();
642 foreach (string key in data) {
643 byte [] bytes = Encoding.UTF8.GetBytes (key);
644 UrlEncodeAndWrite (tmpStream, bytes);
645 tmpStream.WriteByte ((byte) '=');
646 bytes = Encoding.UTF8.GetBytes (data [key]);
647 UrlEncodeAndWrite (tmpStream, bytes);
648 tmpStream.WriteByte ((byte) '&');
651 int length = (int) tmpStream.Length;
653 tmpStream.SetLength (--length); // remove trailing '&'
655 byte [] buf = tmpStream.GetBuffer ();
656 request.ContentLength = length;
657 using (Stream rqStream = request.GetRequestStream ()) {
658 rqStream.Write (buf, 0, length);
662 return ReadAll (request, userToken);
663 } catch (ThreadInterruptedException) {
669 public string DownloadString (string address)
672 throw new ArgumentNullException ("address");
674 return encoding.GetString (DownloadData (CreateUri (address)));
677 public string DownloadString (Uri address)
680 throw new ArgumentNullException ("address");
682 return encoding.GetString (DownloadData (CreateUri (address)));
685 public string UploadString (string address, string data)
688 throw new ArgumentNullException ("address");
690 throw new ArgumentNullException ("data");
692 byte [] resp = UploadData (address, encoding.GetBytes (data));
693 return encoding.GetString (resp);
696 public string UploadString (string address, string method, string data)
699 throw new ArgumentNullException ("address");
701 throw new ArgumentNullException ("data");
703 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
704 return encoding.GetString (resp);
707 public string UploadString (Uri address, string data)
710 throw new ArgumentNullException ("address");
712 throw new ArgumentNullException ("data");
714 byte [] resp = UploadData (address, encoding.GetBytes (data));
715 return encoding.GetString (resp);
718 public string UploadString (Uri address, string method, string data)
721 throw new ArgumentNullException ("address");
723 throw new ArgumentNullException ("data");
725 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
726 return encoding.GetString (resp);
729 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
730 public event AsyncCompletedEventHandler DownloadFileCompleted;
731 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
732 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
733 public event OpenReadCompletedEventHandler OpenReadCompleted;
734 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
735 public event UploadDataCompletedEventHandler UploadDataCompleted;
736 public event UploadFileCompletedEventHandler UploadFileCompleted;
737 public event UploadProgressChangedEventHandler UploadProgressChanged;
738 public event UploadStringCompletedEventHandler UploadStringCompleted;
739 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
741 Uri CreateUri (string address)
745 if (baseAddress == null)
746 uri = new Uri (address);
748 uri = new Uri (baseAddress, address);
749 return CreateUri (uri);
752 return new Uri (Path.GetFullPath (address));
755 Uri CreateUri (Uri address)
757 Uri result = address;
758 if (baseAddress != null && !result.IsAbsoluteUri) {
760 result = new Uri (baseAddress, result.OriginalString);
762 return result; // Not much we can do here.
766 string query = result.Query;
767 if (String.IsNullOrEmpty (query))
768 query = GetQueryString (true);
769 UriBuilder builder = new UriBuilder (address);
770 if (!String.IsNullOrEmpty (query))
771 builder.Query = query.Substring (1);
775 string GetQueryString (bool add_qmark)
777 if (queryString == null || queryString.Count == 0)
780 StringBuilder sb = new StringBuilder ();
784 foreach (string key in queryString)
785 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
788 sb.Length--; // removes last '&' or the '?' if empty.
793 return sb.ToString ();
796 WebRequest SetupRequest (Uri uri)
798 WebRequest request = GetWebRequest (uri);
800 request.Proxy = Proxy;
801 if (credentials != null)
802 request.Credentials = credentials;
803 else if (!String.IsNullOrEmpty (uri.UserInfo)) {
804 // Perhaps this should be done by the underlying URI handler?
805 ICredentials creds = GetCredentials (uri.UserInfo);
807 request.Credentials = creds;
810 // Special headers. These are properties of HttpWebRequest.
811 // What do we do with other requests differnt from HttpWebRequest?
812 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
813 HttpWebRequest req = (HttpWebRequest) request;
814 string expect = headers ["Expect"];
815 string contentType = headers ["Content-Type"];
816 string accept = headers ["Accept"];
817 string connection = headers ["Connection"];
818 string userAgent = headers ["User-Agent"];
819 string referer = headers ["Referer"];
820 headers.RemoveInternal ("Expect");
821 headers.RemoveInternal ("Content-Type");
822 headers.RemoveInternal ("Accept");
823 headers.RemoveInternal ("Connection");
824 headers.RemoveInternal ("Referer");
825 headers.RemoveInternal ("User-Agent");
826 request.Headers = headers;
828 if (expect != null && expect.Length > 0)
831 if (accept != null && accept.Length > 0)
834 if (contentType != null && contentType.Length > 0)
835 req.ContentType = contentType;
837 if (connection != null && connection.Length > 0)
838 req.Connection = connection;
840 if (userAgent != null && userAgent.Length > 0)
841 req.UserAgent = userAgent;
843 if (referer != null && referer.Length > 0)
844 req.Referer = referer;
847 responseHeaders = null;
851 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
853 WebRequest request = SetupRequest (uri);
854 request.Method = DetermineMethod (uri, method, is_upload);
858 static NetworkCredential GetCredentials (string user_info)
860 string [] creds = user_info.Split (':');
861 if (creds.Length != 2)
864 if (creds [0].IndexOf ('\\') != -1) {
865 string [] user = creds [0].Split ('\\');
866 if (user.Length != 2)
868 return new NetworkCredential (user [1], creds [1], user [0]);
870 return new NetworkCredential (creds [0], creds [1]);
873 byte [] ReadAll (WebRequest request, object userToken)
875 WebResponse response = GetWebResponse (request);
876 Stream stream = response.GetResponseStream ();
877 int length = (int) response.ContentLength;
878 HttpWebRequest wreq = request as HttpWebRequest;
880 if (length > -1 && wreq != null && (int) wreq.AutomaticDecompression != 0) {
881 string content_encoding = ((HttpWebResponse) response).ContentEncoding;
882 if (((content_encoding == "gzip" && (wreq.AutomaticDecompression & DecompressionMethods.GZip) != 0)) ||
883 ((content_encoding == "deflate" && (wreq.AutomaticDecompression & DecompressionMethods.Deflate) != 0)))
887 MemoryStream ms = null;
888 bool nolength = (length == -1);
889 int size = ((nolength) ? 8192 : length);
891 ms = new MemoryStream ();
896 byte [] buffer = new byte [size];
897 while ((nread = stream.Read (buffer, offset, size)) != 0) {
899 ms.Write (buffer, 0, nread);
906 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
911 return ms.ToArray ();
916 string UrlEncode (string str)
918 StringBuilder result = new StringBuilder ();
920 int len = str.Length;
921 for (int i = 0; i < len; i++) {
925 else if ((c < '0' && c != '-' && c != '.') ||
926 (c < 'A' && c > '9') ||
927 (c > 'Z' && c < 'a' && c != '_') ||
930 int idx = ((int) c) >> 4;
931 result.Append ((char) hexBytes [idx]);
932 idx = ((int) c) & 0x0F;
933 result.Append ((char) hexBytes [idx]);
939 return result.ToString ();
942 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
947 int len = bytes.Length;
951 for (int i = 0; i < len; i++) {
952 char c = (char) bytes [i];
954 stream.WriteByte ((byte) '+');
955 else if ((c < '0' && c != '-' && c != '.') ||
956 (c < 'A' && c > '9') ||
957 (c > 'Z' && c < 'a' && c != '_') ||
959 stream.WriteByte ((byte) '%');
960 int idx = ((int) c) >> 4;
961 stream.WriteByte (hexBytes [idx]);
962 idx = ((int) c) & 0x0F;
963 stream.WriteByte (hexBytes [idx]);
965 stream.WriteByte ((byte) c);
970 public void CancelAsync ()
973 if (async_thread == null)
977 // We first flag things as done, in case the Interrupt hangs
978 // or the thread decides to hang in some other way inside the
979 // event handlers, or if we are stuck somewhere else. This
980 // ensures that the WebClient object is reusable immediately
982 Thread t = async_thread;
988 void CompleteAsync ()
998 public void DownloadDataAsync (Uri address)
1000 DownloadDataAsync (address, null);
1003 public void DownloadDataAsync (Uri address, object userToken)
1005 if (address == null)
1006 throw new ArgumentNullException ("address");
1012 async_thread = new Thread (delegate (object state) {
1013 object [] args = (object []) state;
1015 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
1016 OnDownloadDataCompleted (
1017 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
1018 } catch (ThreadInterruptedException){
1019 OnDownloadDataCompleted (
1020 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
1022 } catch (Exception e){
1023 OnDownloadDataCompleted (
1024 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
1027 object [] cb_args = new object [] {address, userToken};
1028 async_thread.Start (cb_args);
1032 // DownloadFileAsync
1034 public void DownloadFileAsync (Uri address, string fileName)
1036 DownloadFileAsync (address, fileName, null);
1039 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1041 if (address == null)
1042 throw new ArgumentNullException ("address");
1043 if (fileName == null)
1044 throw new ArgumentNullException ("fileName");
1050 async_thread = new Thread (delegate (object state) {
1051 object [] args = (object []) state;
1053 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1054 OnDownloadFileCompleted (
1055 new AsyncCompletedEventArgs (null, false, args [2]));
1056 } catch (ThreadInterruptedException){
1057 OnDownloadFileCompleted (
1058 new AsyncCompletedEventArgs (null, true, args [2]));
1059 } catch (Exception e){
1060 OnDownloadFileCompleted (
1061 new AsyncCompletedEventArgs (e, false, args [2]));
1063 object [] cb_args = new object [] {address, fileName, userToken};
1064 async_thread.Start (cb_args);
1068 // DownloadStringAsync
1070 public void DownloadStringAsync (Uri address)
1072 DownloadStringAsync (address, null);
1075 public void DownloadStringAsync (Uri address, object userToken)
1077 if (address == null)
1078 throw new ArgumentNullException ("address");
1084 async_thread = new Thread (delegate (object state) {
1085 object [] args = (object []) state;
1087 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1088 OnDownloadStringCompleted (
1089 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1090 } catch (ThreadInterruptedException){
1091 OnDownloadStringCompleted (
1092 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1093 } catch (Exception e){
1094 OnDownloadStringCompleted (
1095 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1097 object [] cb_args = new object [] {address, userToken};
1098 async_thread.Start (cb_args);
1104 public void OpenReadAsync (Uri address)
1106 OpenReadAsync (address, null);
1109 public void OpenReadAsync (Uri address, object userToken)
1111 if (address == null)
1112 throw new ArgumentNullException ("address");
1118 async_thread = new Thread (delegate (object state) {
1119 object [] args = (object []) state;
1120 WebRequest request = null;
1122 request = SetupRequest ((Uri) args [0]);
1123 WebResponse response = GetWebResponse (request);
1124 Stream stream = response.GetResponseStream ();
1125 OnOpenReadCompleted (
1126 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1127 } catch (ThreadInterruptedException){
1128 if (request != null)
1131 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1132 } catch (Exception e){
1133 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1135 object [] cb_args = new object [] {address, userToken};
1136 async_thread.Start (cb_args);
1142 public void OpenWriteAsync (Uri address)
1144 OpenWriteAsync (address, null);
1147 public void OpenWriteAsync (Uri address, string method)
1149 OpenWriteAsync (address, method, null);
1152 public void OpenWriteAsync (Uri address, string method, object userToken)
1154 if (address == null)
1155 throw new ArgumentNullException ("address");
1161 async_thread = new Thread (delegate (object state) {
1162 object [] args = (object []) state;
1163 WebRequest request = null;
1165 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1166 Stream stream = request.GetRequestStream ();
1167 OnOpenWriteCompleted (
1168 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1169 } catch (ThreadInterruptedException){
1170 if (request != null)
1172 OnOpenWriteCompleted (
1173 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1174 } catch (Exception e){
1175 OnOpenWriteCompleted (
1176 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1178 object [] cb_args = new object [] {address, method, userToken};
1179 async_thread.Start (cb_args);
1185 public void UploadDataAsync (Uri address, byte [] data)
1187 UploadDataAsync (address, null, data);
1190 public void UploadDataAsync (Uri address, string method, byte [] data)
1192 UploadDataAsync (address, method, data, null);
1195 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1197 if (address == null)
1198 throw new ArgumentNullException ("address");
1200 throw new ArgumentNullException ("data");
1206 async_thread = new Thread (delegate (object state) {
1207 object [] args = (object []) state;
1211 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1213 OnUploadDataCompleted (
1214 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1215 } catch (ThreadInterruptedException){
1216 OnUploadDataCompleted (
1217 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1218 } catch (Exception e){
1219 OnUploadDataCompleted (
1220 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1222 object [] cb_args = new object [] {address, method, data, userToken};
1223 async_thread.Start (cb_args);
1229 public void UploadFileAsync (Uri address, string fileName)
1231 UploadFileAsync (address, null, fileName);
1234 public void UploadFileAsync (Uri address, string method, string fileName)
1236 UploadFileAsync (address, method, fileName, null);
1239 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1241 if (address == null)
1242 throw new ArgumentNullException ("address");
1243 if (fileName == null)
1244 throw new ArgumentNullException ("fileName");
1250 async_thread = new Thread (delegate (object state) {
1251 object [] args = (object []) state;
1255 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1256 OnUploadFileCompleted (
1257 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1258 } catch (ThreadInterruptedException){
1259 OnUploadFileCompleted (
1260 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1261 } catch (Exception e){
1262 OnUploadFileCompleted (
1263 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1265 object [] cb_args = new object [] {address, method, fileName, userToken};
1266 async_thread.Start (cb_args);
1270 // UploadStringAsync
1272 public void UploadStringAsync (Uri address, string data)
1274 UploadStringAsync (address, null, data);
1277 public void UploadStringAsync (Uri address, string method, string data)
1279 UploadStringAsync (address, method, data, null);
1282 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1284 if (address == null)
1285 throw new ArgumentNullException ("address");
1287 throw new ArgumentNullException ("data");
1293 async_thread = new Thread (delegate (object state) {
1294 object [] args = (object []) state;
1297 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1298 OnUploadStringCompleted (
1299 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1300 } catch (ThreadInterruptedException){
1301 OnUploadStringCompleted (
1302 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1303 } catch (Exception e){
1304 OnUploadStringCompleted (
1305 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1307 object [] cb_args = new object [] {address, method, data, userToken};
1308 async_thread.Start (cb_args);
1312 // UploadValuesAsync
1314 public void UploadValuesAsync (Uri address, NameValueCollection data)
1316 UploadValuesAsync (address, null, data);
1319 public void UploadValuesAsync (Uri address, string method, NameValueCollection data)
1321 UploadValuesAsync (address, method, data, null);
1324 public void UploadValuesAsync (Uri address, string method, NameValueCollection data, object userToken)
1326 if (address == null)
1327 throw new ArgumentNullException ("address");
1329 throw new ArgumentNullException ("data");
1335 async_thread = new Thread (delegate (object state) {
1336 object [] args = (object []) state;
1338 byte [] values = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1339 OnUploadValuesCompleted (
1340 new UploadValuesCompletedEventArgs (values, null, false, args [3]));
1341 } catch (ThreadInterruptedException){
1342 OnUploadValuesCompleted (
1343 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1344 } catch (Exception e){
1345 OnUploadValuesCompleted (
1346 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1348 object [] cb_args = new object [] {address, method, data, userToken};
1349 async_thread.Start (cb_args);
1353 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs e)
1356 if (DownloadDataCompleted != null)
1357 DownloadDataCompleted (this, e);
1360 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs e)
1363 if (DownloadFileCompleted != null)
1364 DownloadFileCompleted (this, e);
1367 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1369 if (DownloadProgressChanged != null)
1370 DownloadProgressChanged (this, e);
1373 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs e)
1376 if (DownloadStringCompleted != null)
1377 DownloadStringCompleted (this, e);
1380 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs e)
1383 if (OpenReadCompleted != null)
1384 OpenReadCompleted (this, e);
1387 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs e)
1390 if (OpenWriteCompleted != null)
1391 OpenWriteCompleted (this, e);
1394 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs e)
1397 if (UploadDataCompleted != null)
1398 UploadDataCompleted (this, e);
1401 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs e)
1404 if (UploadFileCompleted != null)
1405 UploadFileCompleted (this, e);
1408 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1410 if (UploadProgressChanged != null)
1411 UploadProgressChanged (this, e);
1414 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs e)
1417 if (UploadStringCompleted != null)
1418 UploadStringCompleted (this, e);
1421 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs e)
1424 if (UploadValuesCompleted != null)
1425 UploadValuesCompleted (this, e);
1428 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1430 WebResponse response = request.EndGetResponse (result);
1431 responseHeaders = response.Headers;
1435 protected virtual WebRequest GetWebRequest (Uri address)
1437 return WebRequest.Create (address);
1440 protected virtual WebResponse GetWebResponse (WebRequest request)
1442 WebResponse response = request.GetResponse ();
1443 responseHeaders = response.Headers;