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;
87 Encoding encoding = Encoding.Default;
89 RequestCachePolicy cache_policy;
94 hexBytes = new byte [16];
96 for (int i = '0'; i <= '9'; i++, index++)
97 hexBytes [index] = (byte) i;
99 for (int i = 'a'; i <= 'f'; i++, index++)
100 hexBytes [index] = (byte) i;
109 public string BaseAddress {
111 if (baseString == null) {
112 if (baseAddress == null)
116 baseString = baseAddress.ToString ();
121 if (value == null || value.Length == 0) {
124 baseAddress = new Uri (value);
129 static Exception GetMustImplement ()
131 return new NotImplementedException ();
134 [MonoTODO ("Value can be set but is currently ignored")]
135 public RequestCachePolicy CachePolicy
138 throw GetMustImplement ();
140 set { cache_policy = value; }
143 [MonoTODO ("Value can be set but is ignored")]
144 public bool UseDefaultCredentials
147 throw GetMustImplement ();
150 // This makes no sense in mono
154 public ICredentials Credentials {
155 get { return credentials; }
156 set { credentials = value; }
159 public WebHeaderCollection Headers {
162 headers = new WebHeaderCollection ();
166 set { headers = value; }
169 public NameValueCollection QueryString {
171 if (queryString == null)
172 queryString = new NameValueCollection ();
176 set { queryString = value; }
179 public WebHeaderCollection ResponseHeaders {
180 get { return responseHeaders; }
183 public Encoding Encoding {
184 get { return encoding; }
187 throw new ArgumentNullException ("Encoding");
192 public IWebProxy Proxy {
193 get { return proxy; }
194 set { proxy = value; }
198 get { return is_busy; }
205 throw new NotSupportedException ("WebClient does not support conccurent I/O operations.");
218 public byte [] DownloadData (string address)
221 throw new ArgumentNullException ("address");
223 return DownloadData (CreateUri (address));
226 public byte [] DownloadData (Uri address)
229 throw new ArgumentNullException ("address");
234 return DownloadDataCore (address, null);
240 byte [] DownloadDataCore (Uri address, object userToken)
242 WebRequest request = null;
245 request = SetupRequest (address);
246 return ReadAll (request, userToken);
247 } catch (ThreadInterruptedException){
251 } catch (WebException) {
253 } catch (Exception ex) {
254 throw new WebException ("An error occurred " +
255 "performing a WebClient request.", ex);
261 public void DownloadFile (string address, string fileName)
264 throw new ArgumentNullException ("address");
266 DownloadFile (CreateUri (address), fileName);
269 public void DownloadFile (Uri address, string fileName)
272 throw new ArgumentNullException ("address");
273 if (fileName == null)
274 throw new ArgumentNullException ("fileName");
279 DownloadFileCore (address, fileName, null);
280 } catch (WebException) {
282 } catch (Exception ex) {
283 throw new WebException ("An error occurred " +
284 "performing a WebClient request.", ex);
290 void DownloadFileCore (Uri address, string fileName, object userToken)
292 WebRequest request = null;
294 using (FileStream f = new FileStream (fileName, FileMode.Create)) {
296 request = SetupRequest (address);
297 WebResponse response = GetWebResponse (request);
298 Stream st = response.GetResponseStream ();
300 int cLength = (int) response.ContentLength;
301 int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
302 byte [] buffer = new byte [length];
305 long notify_total = 0;
306 while ((nread = st.Read (buffer, 0, length)) != 0){
308 notify_total += nread;
309 OnDownloadProgressChanged (
310 new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
313 f.Write (buffer, 0, nread);
315 } catch (ThreadInterruptedException){
325 public Stream OpenRead (string address)
328 throw new ArgumentNullException ("address");
329 return OpenRead (CreateUri (address));
332 public Stream OpenRead (Uri address)
335 throw new ArgumentNullException ("address");
337 WebRequest request = null;
341 request = SetupRequest (address);
342 WebResponse response = GetWebResponse (request);
343 return response.GetResponseStream ();
344 } catch (WebException) {
346 } catch (Exception ex) {
347 throw new WebException ("An error occurred " +
348 "performing a WebClient request.", ex);
356 public Stream OpenWrite (string address)
359 throw new ArgumentNullException ("address");
361 return OpenWrite (CreateUri (address));
364 public Stream OpenWrite (string address, string method)
367 throw new ArgumentNullException ("address");
369 return OpenWrite (CreateUri (address), method);
372 public Stream OpenWrite (Uri address)
374 return OpenWrite (address, (string) null);
377 public Stream OpenWrite (Uri address, string method)
380 throw new ArgumentNullException ("address");
385 WebRequest request = SetupRequest (address, method, true);
386 return request.GetRequestStream ();
387 } catch (WebException) {
389 } catch (Exception ex) {
390 throw new WebException ("An error occurred " +
391 "performing a WebClient request.", ex);
397 private string DetermineMethod (Uri address, string method, bool is_upload)
402 if (address.Scheme == Uri.UriSchemeFtp)
403 return (is_upload) ? "STOR" : "RETR";
405 return (is_upload) ? "POST" : "GET";
410 public byte [] UploadData (string address, byte [] data)
413 throw new ArgumentNullException ("address");
415 return UploadData (CreateUri (address), data);
418 public byte [] UploadData (string address, string method, byte [] data)
421 throw new ArgumentNullException ("address");
423 return UploadData (CreateUri (address), method, data);
426 public byte [] UploadData (Uri address, byte [] data)
428 return UploadData (address, (string) null, data);
431 public byte [] UploadData (Uri address, string method, byte [] data)
434 throw new ArgumentNullException ("address");
436 throw new ArgumentNullException ("data");
441 return UploadDataCore (address, method, data, null);
442 } catch (WebException) {
444 } catch (Exception ex) {
445 throw new WebException ("An error occurred " +
446 "performing a WebClient request.", ex);
452 byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
454 WebRequest request = SetupRequest (address, method, true);
456 int contentLength = data.Length;
457 request.ContentLength = contentLength;
458 using (Stream stream = request.GetRequestStream ()) {
459 stream.Write (data, 0, contentLength);
462 return ReadAll (request, userToken);
463 } catch (ThreadInterruptedException){
472 public byte [] UploadFile (string address, string fileName)
475 throw new ArgumentNullException ("address");
477 return UploadFile (CreateUri (address), fileName);
480 public byte [] UploadFile (Uri address, string fileName)
482 return UploadFile (address, (string) null, fileName);
485 public byte [] UploadFile (string address, string method, string fileName)
487 return UploadFile (CreateUri (address), method, fileName);
490 public byte [] UploadFile (Uri address, string method, string fileName)
493 throw new ArgumentNullException ("address");
494 if (fileName == null)
495 throw new ArgumentNullException ("fileName");
500 return UploadFileCore (address, method, fileName, null);
501 } catch (WebException) {
503 } catch (Exception ex) {
504 throw new WebException ("An error occurred " +
505 "performing a WebClient request.", ex);
511 byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
513 string fileCType = Headers ["Content-Type"];
514 if (fileCType != null) {
515 string lower = fileCType.ToLower ();
516 if (lower.StartsWith ("multipart/"))
517 throw new WebException ("Content-Type cannot be set to a multipart" +
518 " type for this request.");
520 fileCType = "application/octet-stream";
523 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
524 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
525 Stream reqStream = null;
526 Stream fStream = null;
527 byte [] resultBytes = null;
529 fileName = Path.GetFullPath (fileName);
531 WebRequest request = null;
533 fStream = File.OpenRead (fileName);
534 request = SetupRequest (address, method, true);
535 reqStream = request.GetRequestStream ();
536 byte [] realBoundary = Encoding.ASCII.GetBytes ("--" + boundary + "\r\n");
537 reqStream.Write (realBoundary, 0, realBoundary.Length);
538 string partHeaders = String.Format ("Content-Disposition: form-data; " +
539 "name=\"file\"; filename=\"{0}\"\r\n" +
540 "Content-Type: {1}\r\n\r\n",
541 Path.GetFileName (fileName), fileCType);
543 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
544 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
546 byte [] buffer = new byte [4096];
547 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
548 reqStream.Write (buffer, 0, nread);
550 reqStream.WriteByte ((byte) '\r');
551 reqStream.WriteByte ((byte) '\n');
552 reqStream.Write (realBoundary, 0, realBoundary.Length);
555 resultBytes = ReadAll (request, userToken);
556 } catch (ThreadInterruptedException){
564 if (reqStream != null)
571 public byte[] UploadValues (string address, NameValueCollection data)
574 throw new ArgumentNullException ("address");
576 return UploadValues (CreateUri (address), data);
579 public byte[] UploadValues (string address, string method, NameValueCollection data)
582 throw new ArgumentNullException ("address");
583 return UploadValues (CreateUri (address), method, data);
586 public byte[] UploadValues (Uri address, NameValueCollection data)
588 return UploadValues (address, (string) null, data);
591 public byte[] UploadValues (Uri address, string method, NameValueCollection data)
594 throw new ArgumentNullException ("address");
596 throw new ArgumentNullException ("data");
601 return UploadValuesCore (address, method, data, null);
602 } catch (WebException) {
604 } catch (Exception ex) {
605 throw new WebException ("An error occurred " +
606 "performing a WebClient request.", ex);
612 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
614 string cType = Headers ["Content-Type"];
615 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
616 throw new WebException ("Content-Type header cannot be changed from its default " +
617 "value for this request.");
619 Headers ["Content-Type"] = urlEncodedCType;
620 WebRequest request = SetupRequest (uri, method, true);
622 MemoryStream tmpStream = new MemoryStream ();
623 foreach (string key in data) {
624 byte [] bytes = Encoding.UTF8.GetBytes (key);
625 UrlEncodeAndWrite (tmpStream, bytes);
626 tmpStream.WriteByte ((byte) '=');
627 bytes = Encoding.UTF8.GetBytes (data [key]);
628 UrlEncodeAndWrite (tmpStream, bytes);
629 tmpStream.WriteByte ((byte) '&');
632 int length = (int) tmpStream.Length;
634 tmpStream.SetLength (--length); // remove trailing '&'
636 byte [] buf = tmpStream.GetBuffer ();
637 request.ContentLength = length;
638 using (Stream rqStream = request.GetRequestStream ()) {
639 rqStream.Write (buf, 0, length);
643 return ReadAll (request, userToken);
644 } catch (ThreadInterruptedException) {
650 public string DownloadString (string address)
653 throw new ArgumentNullException ("address");
655 return encoding.GetString (DownloadData (CreateUri (address)));
658 public string DownloadString (Uri address)
661 throw new ArgumentNullException ("address");
663 return encoding.GetString (DownloadData (CreateUri (address)));
666 public string UploadString (string address, string data)
669 throw new ArgumentNullException ("address");
671 throw new ArgumentNullException ("data");
673 byte [] resp = UploadData (address, encoding.GetBytes (data));
674 return encoding.GetString (resp);
677 public string UploadString (string address, string method, string data)
680 throw new ArgumentNullException ("address");
682 throw new ArgumentNullException ("data");
684 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
685 return encoding.GetString (resp);
688 public string UploadString (Uri address, string data)
691 throw new ArgumentNullException ("address");
693 throw new ArgumentNullException ("data");
695 byte [] resp = UploadData (address, encoding.GetBytes (data));
696 return encoding.GetString (resp);
699 public string UploadString (Uri address, string method, string data)
702 throw new ArgumentNullException ("address");
704 throw new ArgumentNullException ("data");
706 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
707 return encoding.GetString (resp);
710 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
711 public event AsyncCompletedEventHandler DownloadFileCompleted;
712 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
713 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
714 public event OpenReadCompletedEventHandler OpenReadCompleted;
715 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
716 public event UploadDataCompletedEventHandler UploadDataCompleted;
717 public event UploadFileCompletedEventHandler UploadFileCompleted;
718 public event UploadProgressChangedEventHandler UploadProgressChanged;
719 public event UploadStringCompletedEventHandler UploadStringCompleted;
720 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
722 Uri CreateUri (string address)
726 if (baseAddress == null)
727 uri = new Uri (address);
729 uri = new Uri (baseAddress, address);
730 return CreateUri (uri);
733 return new Uri (Path.GetFullPath (address));
736 Uri CreateUri (Uri address)
738 Uri result = address;
739 if (baseAddress != null && !result.IsAbsoluteUri) {
741 result = new Uri (baseAddress, result.OriginalString);
743 return result; // Not much we can do here.
747 string query = result.Query;
748 if (String.IsNullOrEmpty (query))
749 query = GetQueryString (true);
750 UriBuilder builder = new UriBuilder (address);
751 if (!String.IsNullOrEmpty (query))
752 builder.Query = query.Substring (1);
756 string GetQueryString (bool add_qmark)
758 if (queryString == null || queryString.Count == 0)
761 StringBuilder sb = new StringBuilder ();
765 foreach (string key in queryString)
766 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
769 sb.Length--; // removes last '&' or the '?' if empty.
774 return sb.ToString ();
777 WebRequest SetupRequest (Uri uri)
779 WebRequest request = GetWebRequest (uri);
781 request.Proxy = Proxy;
782 request.Credentials = credentials;
784 // Special headers. These are properties of HttpWebRequest.
785 // What do we do with other requests differnt from HttpWebRequest?
786 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
787 HttpWebRequest req = (HttpWebRequest) request;
788 string expect = headers ["Expect"];
789 string contentType = headers ["Content-Type"];
790 string accept = headers ["Accept"];
791 string connection = headers ["Connection"];
792 string userAgent = headers ["User-Agent"];
793 string referer = headers ["Referer"];
794 headers.RemoveInternal ("Expect");
795 headers.RemoveInternal ("Content-Type");
796 headers.RemoveInternal ("Accept");
797 headers.RemoveInternal ("Connection");
798 headers.RemoveInternal ("Referer");
799 headers.RemoveInternal ("User-Agent");
800 request.Headers = headers;
802 if (expect != null && expect.Length > 0)
805 if (accept != null && accept.Length > 0)
808 if (contentType != null && contentType.Length > 0)
809 req.ContentType = contentType;
811 if (connection != null && connection.Length > 0)
812 req.Connection = connection;
814 if (userAgent != null && userAgent.Length > 0)
815 req.UserAgent = userAgent;
817 if (referer != null && referer.Length > 0)
818 req.Referer = referer;
821 responseHeaders = null;
825 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
827 WebRequest request = SetupRequest (uri);
828 request.Method = DetermineMethod (uri, method, is_upload);
832 byte [] ReadAll (WebRequest request, object userToken)
834 WebResponse response = GetWebResponse (request);
835 Stream stream = response.GetResponseStream ();
836 int length = (int) response.ContentLength;
837 HttpWebRequest wreq = request as HttpWebRequest;
839 if (length > -1 && wreq != null && (int) wreq.AutomaticDecompression != 0) {
840 string content_encoding = ((HttpWebResponse) response).ContentEncoding;
841 if (((content_encoding == "gzip" && (wreq.AutomaticDecompression & DecompressionMethods.GZip) != 0)) ||
842 ((content_encoding == "deflate" && (wreq.AutomaticDecompression & DecompressionMethods.Deflate) != 0)))
846 MemoryStream ms = null;
847 bool nolength = (length == -1);
848 int size = ((nolength) ? 8192 : length);
850 ms = new MemoryStream ();
855 byte [] buffer = new byte [size];
856 while ((nread = stream.Read (buffer, offset, size)) != 0) {
858 ms.Write (buffer, 0, nread);
865 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
870 return ms.ToArray ();
875 string UrlEncode (string str)
877 StringBuilder result = new StringBuilder ();
879 int len = str.Length;
880 for (int i = 0; i < len; i++) {
884 else if ((c < '0' && c != '-' && c != '.') ||
885 (c < 'A' && c > '9') ||
886 (c > 'Z' && c < 'a' && c != '_') ||
889 int idx = ((int) c) >> 4;
890 result.Append ((char) hexBytes [idx]);
891 idx = ((int) c) & 0x0F;
892 result.Append ((char) hexBytes [idx]);
898 return result.ToString ();
901 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
906 int len = bytes.Length;
910 for (int i = 0; i < len; i++) {
911 char c = (char) bytes [i];
913 stream.WriteByte ((byte) '+');
914 else if ((c < '0' && c != '-' && c != '.') ||
915 (c < 'A' && c > '9') ||
916 (c > 'Z' && c < 'a' && c != '_') ||
918 stream.WriteByte ((byte) '%');
919 int idx = ((int) c) >> 4;
920 stream.WriteByte (hexBytes [idx]);
921 idx = ((int) c) & 0x0F;
922 stream.WriteByte (hexBytes [idx]);
924 stream.WriteByte ((byte) c);
929 public void CancelAsync ()
932 if (async_thread == null)
936 // We first flag things as done, in case the Interrupt hangs
937 // or the thread decides to hang in some other way inside the
938 // event handlers, or if we are stuck somewhere else. This
939 // ensures that the WebClient object is reusable immediately
941 Thread t = async_thread;
947 void CompleteAsync ()
957 public void DownloadDataAsync (Uri address)
959 DownloadDataAsync (address, null);
962 public void DownloadDataAsync (Uri address, object userToken)
965 throw new ArgumentNullException ("address");
971 async_thread = new Thread (delegate (object state) {
972 object [] args = (object []) state;
974 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
975 OnDownloadDataCompleted (
976 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
977 } catch (ThreadInterruptedException){
978 OnDownloadDataCompleted (
979 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
981 } catch (Exception e){
982 OnDownloadDataCompleted (
983 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
986 object [] cb_args = new object [] {address, userToken};
987 async_thread.Start (cb_args);
993 public void DownloadFileAsync (Uri address, string fileName)
995 DownloadFileAsync (address, fileName, null);
998 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1000 if (address == null)
1001 throw new ArgumentNullException ("address");
1002 if (fileName == null)
1003 throw new ArgumentNullException ("fileName");
1009 async_thread = new Thread (delegate (object state) {
1010 object [] args = (object []) state;
1012 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1013 OnDownloadFileCompleted (
1014 new AsyncCompletedEventArgs (null, false, args [2]));
1015 } catch (ThreadInterruptedException){
1016 OnDownloadFileCompleted (
1017 new AsyncCompletedEventArgs (null, true, args [2]));
1018 } catch (Exception e){
1019 OnDownloadFileCompleted (
1020 new AsyncCompletedEventArgs (e, false, args [2]));
1022 object [] cb_args = new object [] {address, fileName, userToken};
1023 async_thread.Start (cb_args);
1027 // DownloadStringAsync
1029 public void DownloadStringAsync (Uri address)
1031 DownloadStringAsync (address, null);
1034 public void DownloadStringAsync (Uri address, object userToken)
1036 if (address == null)
1037 throw new ArgumentNullException ("address");
1043 async_thread = new Thread (delegate (object state) {
1044 object [] args = (object []) state;
1046 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1047 OnDownloadStringCompleted (
1048 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1049 } catch (ThreadInterruptedException){
1050 OnDownloadStringCompleted (
1051 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1052 } catch (Exception e){
1053 OnDownloadStringCompleted (
1054 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1056 object [] cb_args = new object [] {address, userToken};
1057 async_thread.Start (cb_args);
1063 public void OpenReadAsync (Uri address)
1065 OpenReadAsync (address, null);
1068 public void OpenReadAsync (Uri address, object userToken)
1070 if (address == null)
1071 throw new ArgumentNullException ("address");
1077 async_thread = new Thread (delegate (object state) {
1078 object [] args = (object []) state;
1079 WebRequest request = null;
1081 request = SetupRequest ((Uri) args [0]);
1082 WebResponse response = GetWebResponse (request);
1083 Stream stream = response.GetResponseStream ();
1084 OnOpenReadCompleted (
1085 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1086 } catch (ThreadInterruptedException){
1087 if (request != null)
1090 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1091 } catch (Exception e){
1092 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1094 object [] cb_args = new object [] {address, userToken};
1095 async_thread.Start (cb_args);
1101 public void OpenWriteAsync (Uri address)
1103 OpenWriteAsync (address, null);
1106 public void OpenWriteAsync (Uri address, string method)
1108 OpenWriteAsync (address, method, null);
1111 public void OpenWriteAsync (Uri address, string method, object userToken)
1113 if (address == null)
1114 throw new ArgumentNullException ("address");
1120 async_thread = new Thread (delegate (object state) {
1121 object [] args = (object []) state;
1122 WebRequest request = null;
1124 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1125 Stream stream = request.GetRequestStream ();
1126 OnOpenWriteCompleted (
1127 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1128 } catch (ThreadInterruptedException){
1129 if (request != null)
1131 OnOpenWriteCompleted (
1132 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1133 } catch (Exception e){
1134 OnOpenWriteCompleted (
1135 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1137 object [] cb_args = new object [] {address, method, userToken};
1138 async_thread.Start (cb_args);
1144 public void UploadDataAsync (Uri address, byte [] data)
1146 UploadDataAsync (address, null, data);
1149 public void UploadDataAsync (Uri address, string method, byte [] data)
1151 UploadDataAsync (address, method, data, null);
1154 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1156 if (address == null)
1157 throw new ArgumentNullException ("address");
1159 throw new ArgumentNullException ("data");
1165 async_thread = new Thread (delegate (object state) {
1166 object [] args = (object []) state;
1170 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1172 OnUploadDataCompleted (
1173 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1174 } catch (ThreadInterruptedException){
1175 OnUploadDataCompleted (
1176 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1177 } catch (Exception e){
1178 OnUploadDataCompleted (
1179 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1181 object [] cb_args = new object [] {address, method, data, userToken};
1182 async_thread.Start (cb_args);
1188 public void UploadFileAsync (Uri address, string fileName)
1190 UploadFileAsync (address, null, fileName);
1193 public void UploadFileAsync (Uri address, string method, string fileName)
1195 UploadFileAsync (address, method, fileName, null);
1198 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1200 if (address == null)
1201 throw new ArgumentNullException ("address");
1202 if (fileName == null)
1203 throw new ArgumentNullException ("fileName");
1209 async_thread = new Thread (delegate (object state) {
1210 object [] args = (object []) state;
1214 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1215 OnUploadFileCompleted (
1216 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1217 } catch (ThreadInterruptedException){
1218 OnUploadFileCompleted (
1219 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1220 } catch (Exception e){
1221 OnUploadFileCompleted (
1222 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1224 object [] cb_args = new object [] {address, method, fileName, userToken};
1225 async_thread.Start (cb_args);
1229 // UploadStringAsync
1231 public void UploadStringAsync (Uri address, string data)
1233 UploadStringAsync (address, null, data);
1236 public void UploadStringAsync (Uri address, string method, string data)
1238 UploadStringAsync (address, method, data, null);
1241 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1243 if (address == null)
1244 throw new ArgumentNullException ("address");
1246 throw new ArgumentNullException ("data");
1252 async_thread = new Thread (delegate (object state) {
1253 object [] args = (object []) state;
1256 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1257 OnUploadStringCompleted (
1258 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1259 } catch (ThreadInterruptedException){
1260 OnUploadStringCompleted (
1261 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1262 } catch (Exception e){
1263 OnUploadStringCompleted (
1264 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1266 object [] cb_args = new object [] {address, method, data, userToken};
1267 async_thread.Start (cb_args);
1271 // UploadValuesAsync
1273 public void UploadValuesAsync (Uri address, NameValueCollection values)
1275 UploadValuesAsync (address, null, values);
1278 public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
1280 UploadValuesAsync (address, method, values, null);
1283 public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
1285 if (address == null)
1286 throw new ArgumentNullException ("address");
1288 throw new ArgumentNullException ("values");
1294 async_thread = new Thread (delegate (object state) {
1295 object [] args = (object []) state;
1297 byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1298 OnUploadValuesCompleted (
1299 new UploadValuesCompletedEventArgs (data, null, false, args [3]));
1300 } catch (ThreadInterruptedException){
1301 OnUploadValuesCompleted (
1302 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1303 } catch (Exception e){
1304 OnUploadValuesCompleted (
1305 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1307 object [] cb_args = new object [] {address, method, values, userToken};
1308 async_thread.Start (cb_args);
1312 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
1315 if (DownloadDataCompleted != null)
1316 DownloadDataCompleted (this, args);
1319 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
1322 if (DownloadFileCompleted != null)
1323 DownloadFileCompleted (this, args);
1326 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1328 if (DownloadProgressChanged != null)
1329 DownloadProgressChanged (this, e);
1332 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
1335 if (DownloadStringCompleted != null)
1336 DownloadStringCompleted (this, args);
1339 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
1342 if (OpenReadCompleted != null)
1343 OpenReadCompleted (this, args);
1346 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
1349 if (OpenWriteCompleted != null)
1350 OpenWriteCompleted (this, args);
1353 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
1356 if (UploadDataCompleted != null)
1357 UploadDataCompleted (this, args);
1360 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
1363 if (UploadFileCompleted != null)
1364 UploadFileCompleted (this, args);
1367 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1369 if (UploadProgressChanged != null)
1370 UploadProgressChanged (this, e);
1373 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
1376 if (UploadStringCompleted != null)
1377 UploadStringCompleted (this, args);
1380 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
1383 if (UploadValuesCompleted != null)
1384 UploadValuesCompleted (this, args);
1387 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1389 WebResponse response = request.EndGetResponse (result);
1390 responseHeaders = response.Headers;
1394 protected virtual WebRequest GetWebRequest (Uri address)
1396 return WebRequest.Create (address);
1399 protected virtual WebResponse GetWebResponse (WebRequest request)
1401 WebResponse response = request.GetResponse ();
1402 responseHeaders = response.Headers;