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 bool needs_boundary = (method != "PUT"); // only verified case so far
533 string boundary = null;
534 if (needs_boundary) {
535 boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
536 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
538 Stream reqStream = null;
539 Stream fStream = null;
540 byte [] resultBytes = null;
542 fileName = Path.GetFullPath (fileName);
544 WebRequest request = null;
546 fStream = File.OpenRead (fileName);
547 request = SetupRequest (address, method, true);
548 reqStream = request.GetRequestStream ();
549 byte [] bytes_boundary = null;
550 if (needs_boundary) {
551 bytes_boundary = Encoding.ASCII.GetBytes (boundary);
552 reqStream.WriteByte ((byte) '-');
553 reqStream.WriteByte ((byte) '-');
554 reqStream.Write (bytes_boundary, 0, bytes_boundary.Length);
555 reqStream.WriteByte ((byte) '\r');
556 reqStream.WriteByte ((byte) '\n');
557 string partHeaders = String.Format ("Content-Disposition: form-data; " +
558 "name=\"file\"; filename=\"{0}\"\r\n" +
559 "Content-Type: {1}\r\n\r\n",
560 Path.GetFileName (fileName), fileCType);
562 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
563 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
566 byte [] buffer = new byte [4096];
567 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
568 reqStream.Write (buffer, 0, nread);
570 if (needs_boundary) {
571 reqStream.WriteByte ((byte) '\r');
572 reqStream.WriteByte ((byte) '\n');
573 reqStream.WriteByte ((byte) '-');
574 reqStream.WriteByte ((byte) '-');
575 reqStream.Write (bytes_boundary, 0, bytes_boundary.Length);
576 reqStream.WriteByte ((byte) '-');
577 reqStream.WriteByte ((byte) '-');
578 reqStream.WriteByte ((byte) '\r');
579 reqStream.WriteByte ((byte) '\n');
583 resultBytes = ReadAll (request, userToken);
584 } catch (ThreadInterruptedException){
592 if (reqStream != null)
599 public byte[] UploadValues (string address, NameValueCollection data)
602 throw new ArgumentNullException ("address");
604 return UploadValues (CreateUri (address), data);
607 public byte[] UploadValues (string address, string method, NameValueCollection data)
610 throw new ArgumentNullException ("address");
611 return UploadValues (CreateUri (address), method, data);
614 public byte[] UploadValues (Uri address, NameValueCollection data)
616 return UploadValues (address, (string) null, data);
619 public byte[] UploadValues (Uri address, string method, NameValueCollection data)
622 throw new ArgumentNullException ("address");
624 throw new ArgumentNullException ("data");
629 return UploadValuesCore (address, method, data, null);
630 } catch (WebException) {
632 } catch (Exception ex) {
633 throw new WebException ("An error occurred " +
634 "performing a WebClient request.", ex);
640 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
642 string cType = Headers ["Content-Type"];
643 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
644 throw new WebException ("Content-Type header cannot be changed from its default " +
645 "value for this request.");
647 Headers ["Content-Type"] = urlEncodedCType;
648 WebRequest request = SetupRequest (uri, method, true);
650 MemoryStream tmpStream = new MemoryStream ();
651 foreach (string key in data) {
652 byte [] bytes = Encoding.UTF8.GetBytes (key);
653 UrlEncodeAndWrite (tmpStream, bytes);
654 tmpStream.WriteByte ((byte) '=');
655 bytes = Encoding.UTF8.GetBytes (data [key]);
656 UrlEncodeAndWrite (tmpStream, bytes);
657 tmpStream.WriteByte ((byte) '&');
660 int length = (int) tmpStream.Length;
662 tmpStream.SetLength (--length); // remove trailing '&'
664 byte [] buf = tmpStream.GetBuffer ();
665 request.ContentLength = length;
666 using (Stream rqStream = request.GetRequestStream ()) {
667 rqStream.Write (buf, 0, length);
671 return ReadAll (request, userToken);
672 } catch (ThreadInterruptedException) {
678 public string DownloadString (string address)
681 throw new ArgumentNullException ("address");
683 return encoding.GetString (DownloadData (CreateUri (address)));
686 public string DownloadString (Uri address)
689 throw new ArgumentNullException ("address");
691 return encoding.GetString (DownloadData (CreateUri (address)));
694 public string UploadString (string address, string data)
697 throw new ArgumentNullException ("address");
699 throw new ArgumentNullException ("data");
701 byte [] resp = UploadData (address, encoding.GetBytes (data));
702 return encoding.GetString (resp);
705 public string UploadString (string address, string method, string data)
708 throw new ArgumentNullException ("address");
710 throw new ArgumentNullException ("data");
712 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
713 return encoding.GetString (resp);
716 public string UploadString (Uri address, string data)
719 throw new ArgumentNullException ("address");
721 throw new ArgumentNullException ("data");
723 byte [] resp = UploadData (address, encoding.GetBytes (data));
724 return encoding.GetString (resp);
727 public string UploadString (Uri address, string method, string data)
730 throw new ArgumentNullException ("address");
732 throw new ArgumentNullException ("data");
734 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
735 return encoding.GetString (resp);
738 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
739 public event AsyncCompletedEventHandler DownloadFileCompleted;
740 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
741 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
742 public event OpenReadCompletedEventHandler OpenReadCompleted;
743 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
744 public event UploadDataCompletedEventHandler UploadDataCompleted;
745 public event UploadFileCompletedEventHandler UploadFileCompleted;
746 public event UploadProgressChangedEventHandler UploadProgressChanged;
747 public event UploadStringCompletedEventHandler UploadStringCompleted;
748 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
750 Uri CreateUri (string address)
754 if (baseAddress == null)
755 uri = new Uri (address);
757 uri = new Uri (baseAddress, address);
758 return CreateUri (uri);
761 return new Uri (Path.GetFullPath (address));
764 Uri CreateUri (Uri address)
766 Uri result = address;
767 if (baseAddress != null && !result.IsAbsoluteUri) {
769 result = new Uri (baseAddress, result.OriginalString);
771 return result; // Not much we can do here.
775 string query = result.Query;
776 if (String.IsNullOrEmpty (query))
777 query = GetQueryString (true);
778 UriBuilder builder = new UriBuilder (address);
779 if (!String.IsNullOrEmpty (query))
780 builder.Query = query.Substring (1);
784 string GetQueryString (bool add_qmark)
786 if (queryString == null || queryString.Count == 0)
789 StringBuilder sb = new StringBuilder ();
793 foreach (string key in queryString)
794 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
797 sb.Length--; // removes last '&' or the '?' if empty.
802 return sb.ToString ();
805 WebRequest SetupRequest (Uri uri)
807 WebRequest request = GetWebRequest (uri);
809 request.Proxy = Proxy;
810 if (credentials != null)
811 request.Credentials = credentials;
812 else if (!String.IsNullOrEmpty (uri.UserInfo)) {
813 // Perhaps this should be done by the underlying URI handler?
814 ICredentials creds = GetCredentials (uri.UserInfo);
816 request.Credentials = creds;
819 // Special headers. These are properties of HttpWebRequest.
820 // What do we do with other requests differnt from HttpWebRequest?
821 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
822 HttpWebRequest req = (HttpWebRequest) request;
823 string expect = headers ["Expect"];
824 string contentType = headers ["Content-Type"];
825 string accept = headers ["Accept"];
826 string connection = headers ["Connection"];
827 string userAgent = headers ["User-Agent"];
828 string referer = headers ["Referer"];
829 headers.RemoveInternal ("Expect");
830 headers.RemoveInternal ("Content-Type");
831 headers.RemoveInternal ("Accept");
832 headers.RemoveInternal ("Connection");
833 headers.RemoveInternal ("Referer");
834 headers.RemoveInternal ("User-Agent");
835 request.Headers = headers;
837 if (expect != null && expect.Length > 0)
840 if (accept != null && accept.Length > 0)
843 if (contentType != null && contentType.Length > 0)
844 req.ContentType = contentType;
846 if (connection != null && connection.Length > 0)
847 req.Connection = connection;
849 if (userAgent != null && userAgent.Length > 0)
850 req.UserAgent = userAgent;
852 if (referer != null && referer.Length > 0)
853 req.Referer = referer;
856 responseHeaders = null;
860 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
862 WebRequest request = SetupRequest (uri);
863 request.Method = DetermineMethod (uri, method, is_upload);
867 static NetworkCredential GetCredentials (string user_info)
869 string [] creds = user_info.Split (':');
870 if (creds.Length != 2)
873 if (creds [0].IndexOf ('\\') != -1) {
874 string [] user = creds [0].Split ('\\');
875 if (user.Length != 2)
877 return new NetworkCredential (user [1], creds [1], user [0]);
879 return new NetworkCredential (creds [0], creds [1]);
882 byte [] ReadAll (WebRequest request, object userToken)
884 WebResponse response = GetWebResponse (request);
885 Stream stream = response.GetResponseStream ();
886 int length = (int) response.ContentLength;
887 HttpWebRequest wreq = request as HttpWebRequest;
889 if (length > -1 && wreq != null && (int) wreq.AutomaticDecompression != 0) {
890 string content_encoding = ((HttpWebResponse) response).ContentEncoding;
891 if (((content_encoding == "gzip" && (wreq.AutomaticDecompression & DecompressionMethods.GZip) != 0)) ||
892 ((content_encoding == "deflate" && (wreq.AutomaticDecompression & DecompressionMethods.Deflate) != 0)))
896 MemoryStream ms = null;
897 bool nolength = (length == -1);
898 int size = ((nolength) ? 8192 : length);
900 ms = new MemoryStream ();
905 byte [] buffer = new byte [size];
906 while ((nread = stream.Read (buffer, offset, size)) != 0) {
908 ms.Write (buffer, 0, nread);
915 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (total, length, userToken));
920 return ms.ToArray ();
925 string UrlEncode (string str)
927 StringBuilder result = new StringBuilder ();
929 int len = str.Length;
930 for (int i = 0; i < len; i++) {
934 else if ((c < '0' && c != '-' && c != '.') ||
935 (c < 'A' && c > '9') ||
936 (c > 'Z' && c < 'a' && c != '_') ||
939 int idx = ((int) c) >> 4;
940 result.Append ((char) hexBytes [idx]);
941 idx = ((int) c) & 0x0F;
942 result.Append ((char) hexBytes [idx]);
948 return result.ToString ();
951 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
956 int len = bytes.Length;
960 for (int i = 0; i < len; i++) {
961 char c = (char) bytes [i];
963 stream.WriteByte ((byte) '+');
964 else if ((c < '0' && c != '-' && c != '.') ||
965 (c < 'A' && c > '9') ||
966 (c > 'Z' && c < 'a' && c != '_') ||
968 stream.WriteByte ((byte) '%');
969 int idx = ((int) c) >> 4;
970 stream.WriteByte (hexBytes [idx]);
971 idx = ((int) c) & 0x0F;
972 stream.WriteByte (hexBytes [idx]);
974 stream.WriteByte ((byte) c);
979 public void CancelAsync ()
982 if (async_thread == null)
986 // We first flag things as done, in case the Interrupt hangs
987 // or the thread decides to hang in some other way inside the
988 // event handlers, or if we are stuck somewhere else. This
989 // ensures that the WebClient object is reusable immediately
991 Thread t = async_thread;
997 void CompleteAsync ()
1001 async_thread = null;
1005 // DownloadDataAsync
1007 public void DownloadDataAsync (Uri address)
1009 DownloadDataAsync (address, null);
1012 public void DownloadDataAsync (Uri address, object userToken)
1014 if (address == null)
1015 throw new ArgumentNullException ("address");
1021 async_thread = new Thread (delegate (object state) {
1022 object [] args = (object []) state;
1024 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
1025 OnDownloadDataCompleted (
1026 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
1027 } catch (ThreadInterruptedException){
1028 OnDownloadDataCompleted (
1029 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
1031 } catch (Exception e){
1032 OnDownloadDataCompleted (
1033 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
1036 object [] cb_args = new object [] {address, userToken};
1037 async_thread.Start (cb_args);
1041 // DownloadFileAsync
1043 public void DownloadFileAsync (Uri address, string fileName)
1045 DownloadFileAsync (address, fileName, null);
1048 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1050 if (address == null)
1051 throw new ArgumentNullException ("address");
1052 if (fileName == null)
1053 throw new ArgumentNullException ("fileName");
1059 async_thread = new Thread (delegate (object state) {
1060 object [] args = (object []) state;
1062 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1063 OnDownloadFileCompleted (
1064 new AsyncCompletedEventArgs (null, false, args [2]));
1065 } catch (ThreadInterruptedException){
1066 OnDownloadFileCompleted (
1067 new AsyncCompletedEventArgs (null, true, args [2]));
1068 } catch (Exception e){
1069 OnDownloadFileCompleted (
1070 new AsyncCompletedEventArgs (e, false, args [2]));
1072 object [] cb_args = new object [] {address, fileName, userToken};
1073 async_thread.Start (cb_args);
1077 // DownloadStringAsync
1079 public void DownloadStringAsync (Uri address)
1081 DownloadStringAsync (address, null);
1084 public void DownloadStringAsync (Uri address, object userToken)
1086 if (address == null)
1087 throw new ArgumentNullException ("address");
1093 async_thread = new Thread (delegate (object state) {
1094 object [] args = (object []) state;
1096 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1097 OnDownloadStringCompleted (
1098 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1099 } catch (ThreadInterruptedException){
1100 OnDownloadStringCompleted (
1101 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1102 } catch (Exception e){
1103 OnDownloadStringCompleted (
1104 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1106 object [] cb_args = new object [] {address, userToken};
1107 async_thread.Start (cb_args);
1113 public void OpenReadAsync (Uri address)
1115 OpenReadAsync (address, null);
1118 public void OpenReadAsync (Uri address, object userToken)
1120 if (address == null)
1121 throw new ArgumentNullException ("address");
1127 async_thread = new Thread (delegate (object state) {
1128 object [] args = (object []) state;
1129 WebRequest request = null;
1131 request = SetupRequest ((Uri) args [0]);
1132 WebResponse response = GetWebResponse (request);
1133 Stream stream = response.GetResponseStream ();
1134 OnOpenReadCompleted (
1135 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1136 } catch (ThreadInterruptedException){
1137 if (request != null)
1140 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1141 } catch (Exception e){
1142 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1144 object [] cb_args = new object [] {address, userToken};
1145 async_thread.Start (cb_args);
1151 public void OpenWriteAsync (Uri address)
1153 OpenWriteAsync (address, null);
1156 public void OpenWriteAsync (Uri address, string method)
1158 OpenWriteAsync (address, method, null);
1161 public void OpenWriteAsync (Uri address, string method, object userToken)
1163 if (address == null)
1164 throw new ArgumentNullException ("address");
1170 async_thread = new Thread (delegate (object state) {
1171 object [] args = (object []) state;
1172 WebRequest request = null;
1174 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1175 Stream stream = request.GetRequestStream ();
1176 OnOpenWriteCompleted (
1177 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1178 } catch (ThreadInterruptedException){
1179 if (request != null)
1181 OnOpenWriteCompleted (
1182 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1183 } catch (Exception e){
1184 OnOpenWriteCompleted (
1185 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1187 object [] cb_args = new object [] {address, method, userToken};
1188 async_thread.Start (cb_args);
1194 public void UploadDataAsync (Uri address, byte [] data)
1196 UploadDataAsync (address, null, data);
1199 public void UploadDataAsync (Uri address, string method, byte [] data)
1201 UploadDataAsync (address, method, data, null);
1204 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1206 if (address == null)
1207 throw new ArgumentNullException ("address");
1209 throw new ArgumentNullException ("data");
1215 async_thread = new Thread (delegate (object state) {
1216 object [] args = (object []) state;
1220 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1222 OnUploadDataCompleted (
1223 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1224 } catch (ThreadInterruptedException){
1225 OnUploadDataCompleted (
1226 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1227 } catch (Exception e){
1228 OnUploadDataCompleted (
1229 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1231 object [] cb_args = new object [] {address, method, data, userToken};
1232 async_thread.Start (cb_args);
1238 public void UploadFileAsync (Uri address, string fileName)
1240 UploadFileAsync (address, null, fileName);
1243 public void UploadFileAsync (Uri address, string method, string fileName)
1245 UploadFileAsync (address, method, fileName, null);
1248 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1250 if (address == null)
1251 throw new ArgumentNullException ("address");
1252 if (fileName == null)
1253 throw new ArgumentNullException ("fileName");
1259 async_thread = new Thread (delegate (object state) {
1260 object [] args = (object []) state;
1264 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1265 OnUploadFileCompleted (
1266 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1267 } catch (ThreadInterruptedException){
1268 OnUploadFileCompleted (
1269 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1270 } catch (Exception e){
1271 OnUploadFileCompleted (
1272 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1274 object [] cb_args = new object [] {address, method, fileName, userToken};
1275 async_thread.Start (cb_args);
1279 // UploadStringAsync
1281 public void UploadStringAsync (Uri address, string data)
1283 UploadStringAsync (address, null, data);
1286 public void UploadStringAsync (Uri address, string method, string data)
1288 UploadStringAsync (address, method, data, null);
1291 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1293 if (address == null)
1294 throw new ArgumentNullException ("address");
1296 throw new ArgumentNullException ("data");
1302 async_thread = new Thread (delegate (object state) {
1303 object [] args = (object []) state;
1306 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1307 OnUploadStringCompleted (
1308 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1309 } catch (ThreadInterruptedException){
1310 OnUploadStringCompleted (
1311 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1312 } catch (Exception e){
1313 OnUploadStringCompleted (
1314 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1316 object [] cb_args = new object [] {address, method, data, userToken};
1317 async_thread.Start (cb_args);
1321 // UploadValuesAsync
1323 public void UploadValuesAsync (Uri address, NameValueCollection data)
1325 UploadValuesAsync (address, null, data);
1328 public void UploadValuesAsync (Uri address, string method, NameValueCollection data)
1330 UploadValuesAsync (address, method, data, null);
1333 public void UploadValuesAsync (Uri address, string method, NameValueCollection data, object userToken)
1335 if (address == null)
1336 throw new ArgumentNullException ("address");
1338 throw new ArgumentNullException ("data");
1344 async_thread = new Thread (delegate (object state) {
1345 object [] args = (object []) state;
1347 byte [] values = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1348 OnUploadValuesCompleted (
1349 new UploadValuesCompletedEventArgs (values, null, false, args [3]));
1350 } catch (ThreadInterruptedException){
1351 OnUploadValuesCompleted (
1352 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1353 } catch (Exception e){
1354 OnUploadValuesCompleted (
1355 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1357 object [] cb_args = new object [] {address, method, data, userToken};
1358 async_thread.Start (cb_args);
1362 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs e)
1365 if (DownloadDataCompleted != null)
1366 DownloadDataCompleted (this, e);
1369 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs e)
1372 if (DownloadFileCompleted != null)
1373 DownloadFileCompleted (this, e);
1376 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1378 if (DownloadProgressChanged != null)
1379 DownloadProgressChanged (this, e);
1382 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs e)
1385 if (DownloadStringCompleted != null)
1386 DownloadStringCompleted (this, e);
1389 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs e)
1392 if (OpenReadCompleted != null)
1393 OpenReadCompleted (this, e);
1396 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs e)
1399 if (OpenWriteCompleted != null)
1400 OpenWriteCompleted (this, e);
1403 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs e)
1406 if (UploadDataCompleted != null)
1407 UploadDataCompleted (this, e);
1410 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs e)
1413 if (UploadFileCompleted != null)
1414 UploadFileCompleted (this, e);
1417 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1419 if (UploadProgressChanged != null)
1420 UploadProgressChanged (this, e);
1423 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs e)
1426 if (UploadStringCompleted != null)
1427 UploadStringCompleted (this, e);
1430 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs e)
1433 if (UploadValuesCompleted != null)
1434 UploadValuesCompleted (this, e);
1437 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1439 WebResponse response = request.EndGetResponse (result);
1440 responseHeaders = response.Headers;
1444 protected virtual WebRequest GetWebRequest (Uri address)
1446 return WebRequest.Create (address);
1449 protected virtual WebResponse GetWebResponse (WebRequest request)
1451 WebResponse response = request.GetResponse ();
1452 responseHeaders = response.Headers;