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;
93 hexBytes = new byte [16];
95 for (int i = '0'; i <= '9'; i++, index++)
96 hexBytes [index] = (byte) i;
98 for (int i = 'a'; i <= 'f'; i++, index++)
99 hexBytes [index] = (byte) i;
108 public string BaseAddress {
110 if (baseString == null) {
111 if (baseAddress == null)
115 baseString = baseAddress.ToString ();
120 if (value == null || value.Length == 0) {
123 baseAddress = new Uri (value);
128 static Exception GetMustImplement ()
130 return new NotImplementedException ();
134 public RequestCachePolicy CachePolicy
137 throw GetMustImplement ();
140 throw GetMustImplement ();
145 public bool UseDefaultCredentials
148 throw GetMustImplement ();
151 throw GetMustImplement ();
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 {
194 get { return proxy; }
195 set { proxy = value; }
199 get { return is_busy; }
206 throw new NotSupportedException ("WebClient does not support conccurent I/O operations.");
219 public byte [] DownloadData (string address)
222 throw new ArgumentNullException ("address");
224 return DownloadData (CreateUri (address));
227 public byte [] DownloadData (Uri address)
230 throw new ArgumentNullException ("address");
235 return DownloadDataCore (address, null);
241 byte [] DownloadDataCore (Uri address, object userToken)
243 WebRequest request = null;
246 request = SetupRequest (address);
247 return ReadAll (request, userToken);
248 } catch (ThreadInterruptedException){
252 } catch (WebException) {
254 } catch (Exception ex) {
255 throw new WebException ("An error occurred " +
256 "performing a WebClient request.", ex);
262 public void DownloadFile (string address, string fileName)
265 throw new ArgumentNullException ("address");
267 DownloadFile (CreateUri (address), fileName);
270 public void DownloadFile (Uri address, string fileName)
273 throw new ArgumentNullException ("address");
274 if (fileName == null)
275 throw new ArgumentNullException ("fileName");
280 DownloadFileCore (address, fileName, null);
281 } catch (WebException) {
283 } catch (Exception ex) {
284 throw new WebException ("An error occurred " +
285 "performing a WebClient request.", ex);
291 void DownloadFileCore (Uri address, string fileName, object userToken)
293 WebRequest request = null;
295 using (FileStream f = new FileStream (fileName, FileMode.Create)) {
297 request = SetupRequest (address);
298 WebResponse response = GetWebResponse (request);
299 Stream st = response.GetResponseStream ();
301 int cLength = (int) response.ContentLength;
302 int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
303 byte [] buffer = new byte [length];
306 long notify_total = 0;
307 while ((nread = st.Read (buffer, 0, length)) != 0){
309 notify_total += nread;
310 OnDownloadProgressChanged (
311 new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
314 f.Write (buffer, 0, nread);
316 } catch (ThreadInterruptedException){
326 public Stream OpenRead (string address)
329 throw new ArgumentNullException ("address");
330 return OpenRead (CreateUri (address));
333 public Stream OpenRead (Uri address)
336 throw new ArgumentNullException ("address");
338 WebRequest request = null;
342 request = SetupRequest (address);
343 WebResponse response = GetWebResponse (request);
344 return response.GetResponseStream ();
345 } catch (WebException) {
347 } catch (Exception ex) {
348 throw new WebException ("An error occurred " +
349 "performing a WebClient request.", ex);
357 public Stream OpenWrite (string address)
360 throw new ArgumentNullException ("address");
362 return OpenWrite (CreateUri (address));
365 public Stream OpenWrite (string address, string method)
368 throw new ArgumentNullException ("address");
370 return OpenWrite (CreateUri (address), method);
373 public Stream OpenWrite (Uri address)
375 return OpenWrite (address, (string) null);
378 public Stream OpenWrite (Uri address, string method)
381 throw new ArgumentNullException ("address");
386 WebRequest request = SetupRequest (address, method, true);
387 return request.GetRequestStream ();
388 } catch (WebException) {
390 } catch (Exception ex) {
391 throw new WebException ("An error occurred " +
392 "performing a WebClient request.", ex);
398 private string DetermineMethod (Uri address, string method, bool is_upload)
403 if (address.Scheme == Uri.UriSchemeFtp)
404 return (is_upload) ? "STOR" : "RETR";
406 return (is_upload) ? "POST" : "GET";
411 public byte [] UploadData (string address, byte [] data)
414 throw new ArgumentNullException ("address");
416 return UploadData (CreateUri (address), data);
419 public byte [] UploadData (string address, string method, byte [] data)
422 throw new ArgumentNullException ("address");
424 return UploadData (CreateUri (address), method, data);
427 public byte [] UploadData (Uri address, byte [] data)
429 return UploadData (address, (string) null, data);
432 public byte [] UploadData (Uri address, string method, byte [] data)
435 throw new ArgumentNullException ("address");
437 throw new ArgumentNullException ("data");
442 return UploadDataCore (address, method, data, null);
443 } catch (WebException) {
445 } catch (Exception ex) {
446 throw new WebException ("An error occurred " +
447 "performing a WebClient request.", ex);
453 byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
455 WebRequest request = SetupRequest (address, method, true);
457 int contentLength = data.Length;
458 request.ContentLength = contentLength;
459 using (Stream stream = request.GetRequestStream ()) {
460 stream.Write (data, 0, contentLength);
463 return ReadAll (request, userToken);
464 } catch (ThreadInterruptedException){
473 public byte [] UploadFile (string address, string fileName)
476 throw new ArgumentNullException ("address");
478 return UploadFile (CreateUri (address), fileName);
481 public byte [] UploadFile (Uri address, string fileName)
483 return UploadFile (address, (string) null, fileName);
486 public byte [] UploadFile (string address, string method, string fileName)
488 return UploadFile (CreateUri (address), method, fileName);
491 public byte [] UploadFile (Uri address, string method, string fileName)
494 throw new ArgumentNullException ("address");
495 if (fileName == null)
496 throw new ArgumentNullException ("fileName");
501 return UploadFileCore (address, method, fileName, null);
502 } catch (WebException) {
504 } catch (Exception ex) {
505 throw new WebException ("An error occurred " +
506 "performing a WebClient request.", ex);
512 byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
514 string fileCType = Headers ["Content-Type"];
515 if (fileCType != null) {
516 string lower = fileCType.ToLower ();
517 if (lower.StartsWith ("multipart/"))
518 throw new WebException ("Content-Type cannot be set to a multipart" +
519 " type for this request.");
521 fileCType = "application/octet-stream";
524 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
525 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
526 Stream reqStream = null;
527 Stream fStream = null;
528 byte [] resultBytes = null;
530 fileName = Path.GetFullPath (fileName);
532 WebRequest request = null;
534 fStream = File.OpenRead (fileName);
535 request = SetupRequest (address, method, true);
536 reqStream = request.GetRequestStream ();
537 byte [] realBoundary = Encoding.ASCII.GetBytes ("--" + boundary + "\r\n");
538 reqStream.Write (realBoundary, 0, realBoundary.Length);
539 string partHeaders = String.Format ("Content-Disposition: form-data; " +
540 "name=\"file\"; filename=\"{0}\"\r\n" +
541 "Content-Type: {1}\r\n\r\n",
542 Path.GetFileName (fileName), fileCType);
544 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
545 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
547 byte [] buffer = new byte [4096];
548 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
549 reqStream.Write (buffer, 0, nread);
551 reqStream.WriteByte ((byte) '\r');
552 reqStream.WriteByte ((byte) '\n');
553 reqStream.Write (realBoundary, 0, realBoundary.Length);
556 resultBytes = ReadAll (request, userToken);
557 } catch (ThreadInterruptedException){
565 if (reqStream != null)
572 public byte[] UploadValues (string address, NameValueCollection data)
575 throw new ArgumentNullException ("address");
577 return UploadValues (CreateUri (address), data);
580 public byte[] UploadValues (string address, string method, NameValueCollection data)
583 throw new ArgumentNullException ("address");
584 return UploadValues (CreateUri (address), method, data);
587 public byte[] UploadValues (Uri address, NameValueCollection data)
589 return UploadValues (address, (string) null, data);
592 public byte[] UploadValues (Uri address, string method, NameValueCollection data)
595 throw new ArgumentNullException ("address");
597 throw new ArgumentNullException ("data");
602 return UploadValuesCore (address, method, data, null);
603 } catch (WebException) {
605 } catch (Exception ex) {
606 throw new WebException ("An error occurred " +
607 "performing a WebClient request.", ex);
613 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
615 string cType = Headers ["Content-Type"];
616 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
617 throw new WebException ("Content-Type header cannot be changed from its default " +
618 "value for this request.");
620 Headers ["Content-Type"] = urlEncodedCType;
621 WebRequest request = SetupRequest (uri, method, true);
623 MemoryStream tmpStream = new MemoryStream ();
624 foreach (string key in data) {
625 byte [] bytes = Encoding.UTF8.GetBytes (key);
626 UrlEncodeAndWrite (tmpStream, bytes);
627 tmpStream.WriteByte ((byte) '=');
628 bytes = Encoding.UTF8.GetBytes (data [key]);
629 UrlEncodeAndWrite (tmpStream, bytes);
630 tmpStream.WriteByte ((byte) '&');
633 int length = (int) tmpStream.Length;
635 tmpStream.SetLength (--length); // remove trailing '&'
637 byte [] buf = tmpStream.GetBuffer ();
638 request.ContentLength = length;
639 using (Stream rqStream = request.GetRequestStream ()) {
640 rqStream.Write (buf, 0, length);
644 return ReadAll (request, userToken);
645 } catch (ThreadInterruptedException) {
651 public string DownloadString (string address)
654 throw new ArgumentNullException ("address");
656 return encoding.GetString (DownloadData (CreateUri (address)));
659 public string DownloadString (Uri address)
662 throw new ArgumentNullException ("address");
664 return encoding.GetString (DownloadData (CreateUri (address)));
667 public string UploadString (string address, string data)
670 throw new ArgumentNullException ("address");
672 throw new ArgumentNullException ("data");
674 byte [] resp = UploadData (address, encoding.GetBytes (data));
675 return encoding.GetString (resp);
678 public string UploadString (string address, string method, string data)
681 throw new ArgumentNullException ("address");
683 throw new ArgumentNullException ("data");
685 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
686 return encoding.GetString (resp);
689 public string UploadString (Uri address, string data)
692 throw new ArgumentNullException ("address");
694 throw new ArgumentNullException ("data");
696 byte [] resp = UploadData (address, encoding.GetBytes (data));
697 return encoding.GetString (resp);
700 public string UploadString (Uri address, string method, string data)
703 throw new ArgumentNullException ("address");
705 throw new ArgumentNullException ("data");
707 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
708 return encoding.GetString (resp);
711 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
712 public event AsyncCompletedEventHandler DownloadFileCompleted;
713 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
714 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
715 public event OpenReadCompletedEventHandler OpenReadCompleted;
716 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
717 public event UploadDataCompletedEventHandler UploadDataCompleted;
718 public event UploadFileCompletedEventHandler UploadFileCompleted;
719 public event UploadProgressChangedEventHandler UploadProgressChanged;
720 public event UploadStringCompletedEventHandler UploadStringCompleted;
721 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
723 Uri CreateUri (string address)
727 if (baseAddress == null)
728 uri = new Uri (address);
730 uri = new Uri (baseAddress, address);
731 return CreateUri (uri);
734 return new Uri (Path.GetFullPath (address));
737 Uri CreateUri (Uri address)
739 Uri result = address;
740 if (baseAddress != null && !result.IsAbsoluteUri) {
742 result = new Uri (baseAddress, result.OriginalString);
744 return result; // Not much we can do here.
748 string query = result.Query;
749 if (String.IsNullOrEmpty (query))
750 query = GetQueryString (true);
751 UriBuilder builder = new UriBuilder (address);
752 if (!String.IsNullOrEmpty (query))
753 builder.Query = query.Substring (1);
757 string GetQueryString (bool add_qmark)
759 if (queryString == null || queryString.Count == 0)
762 StringBuilder sb = new StringBuilder ();
766 foreach (string key in queryString)
767 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
770 sb.Length--; // removes last '&' or the '?' if empty.
775 return sb.ToString ();
778 WebRequest SetupRequest (Uri uri)
780 WebRequest request = GetWebRequest (uri);
782 request.Proxy = Proxy;
783 request.Credentials = credentials;
785 // Special headers. These are properties of HttpWebRequest.
786 // What do we do with other requests differnt from HttpWebRequest?
787 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
788 HttpWebRequest req = (HttpWebRequest) request;
789 string expect = headers ["Expect"];
790 string contentType = headers ["Content-Type"];
791 string accept = headers ["Accept"];
792 string connection = headers ["Connection"];
793 string userAgent = headers ["User-Agent"];
794 string referer = headers ["Referer"];
795 headers.RemoveInternal ("Expect");
796 headers.RemoveInternal ("Content-Type");
797 headers.RemoveInternal ("Accept");
798 headers.RemoveInternal ("Connection");
799 headers.RemoveInternal ("Referer");
800 headers.RemoveInternal ("User-Agent");
801 request.Headers = headers;
803 if (expect != null && expect.Length > 0)
806 if (accept != null && accept.Length > 0)
809 if (contentType != null && contentType.Length > 0)
810 req.ContentType = contentType;
812 if (connection != null && connection.Length > 0)
813 req.Connection = connection;
815 if (userAgent != null && userAgent.Length > 0)
816 req.UserAgent = userAgent;
818 if (referer != null && referer.Length > 0)
819 req.Referer = referer;
822 responseHeaders = null;
826 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
828 WebRequest request = SetupRequest (uri);
829 request.Method = DetermineMethod (uri, method, is_upload);
833 byte [] ReadAll (WebRequest request, object userToken)
835 WebResponse response = GetWebResponse (request);
836 Stream stream = response.GetResponseStream ();
837 int length = (int) response.ContentLength;
838 HttpWebRequest wreq = request as HttpWebRequest;
840 if (length > -1 && wreq != null && (int) wreq.AutomaticDecompression != 0) {
841 string content_encoding = ((HttpWebResponse) response).ContentEncoding;
842 if (((content_encoding == "gzip" && (wreq.AutomaticDecompression & DecompressionMethods.GZip) != 0)) ||
843 ((content_encoding == "deflate" && (wreq.AutomaticDecompression & DecompressionMethods.Deflate) != 0)))
847 MemoryStream ms = null;
848 bool nolength = (length == -1);
849 int size = ((nolength) ? 8192 : length);
851 ms = new MemoryStream ();
856 byte [] buffer = new byte [size];
857 while ((nread = stream.Read (buffer, offset, size)) != 0) {
859 ms.Write (buffer, 0, nread);
866 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
871 return ms.ToArray ();
876 string UrlEncode (string str)
878 StringBuilder result = new StringBuilder ();
880 int len = str.Length;
881 for (int i = 0; i < len; i++) {
885 else if ((c < '0' && c != '-' && c != '.') ||
886 (c < 'A' && c > '9') ||
887 (c > 'Z' && c < 'a' && c != '_') ||
890 int idx = ((int) c) >> 4;
891 result.Append ((char) hexBytes [idx]);
892 idx = ((int) c) & 0x0F;
893 result.Append ((char) hexBytes [idx]);
899 return result.ToString ();
902 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
907 int len = bytes.Length;
911 for (int i = 0; i < len; i++) {
912 char c = (char) bytes [i];
914 stream.WriteByte ((byte) '+');
915 else if ((c < '0' && c != '-' && c != '.') ||
916 (c < 'A' && c > '9') ||
917 (c > 'Z' && c < 'a' && c != '_') ||
919 stream.WriteByte ((byte) '%');
920 int idx = ((int) c) >> 4;
921 stream.WriteByte (hexBytes [idx]);
922 idx = ((int) c) & 0x0F;
923 stream.WriteByte (hexBytes [idx]);
925 stream.WriteByte ((byte) c);
930 public void CancelAsync ()
933 if (async_thread == null)
937 // We first flag things as done, in case the Interrupt hangs
938 // or the thread decides to hang in some other way inside the
939 // event handlers, or if we are stuck somewhere else. This
940 // ensures that the WebClient object is reusable immediately
942 Thread t = async_thread;
948 void CompleteAsync ()
958 public void DownloadDataAsync (Uri address)
960 DownloadDataAsync (address, null);
963 public void DownloadDataAsync (Uri address, object userToken)
966 throw new ArgumentNullException ("address");
972 async_thread = new Thread (delegate (object state) {
973 object [] args = (object []) state;
975 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
976 OnDownloadDataCompleted (
977 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
978 } catch (ThreadInterruptedException){
979 OnDownloadDataCompleted (
980 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
982 } catch (Exception e){
983 OnDownloadDataCompleted (
984 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
987 object [] cb_args = new object [] {address, userToken};
988 async_thread.Start (cb_args);
994 public void DownloadFileAsync (Uri address, string fileName)
996 DownloadFileAsync (address, fileName, null);
999 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1001 if (address == null)
1002 throw new ArgumentNullException ("address");
1003 if (fileName == null)
1004 throw new ArgumentNullException ("fileName");
1010 async_thread = new Thread (delegate (object state) {
1011 object [] args = (object []) state;
1013 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1014 OnDownloadFileCompleted (
1015 new AsyncCompletedEventArgs (null, false, args [2]));
1016 } catch (ThreadInterruptedException){
1017 OnDownloadFileCompleted (
1018 new AsyncCompletedEventArgs (null, true, args [2]));
1019 } catch (Exception e){
1020 OnDownloadFileCompleted (
1021 new AsyncCompletedEventArgs (e, false, args [2]));
1023 object [] cb_args = new object [] {address, fileName, userToken};
1024 async_thread.Start (cb_args);
1028 // DownloadStringAsync
1030 public void DownloadStringAsync (Uri address)
1032 DownloadStringAsync (address, null);
1035 public void DownloadStringAsync (Uri address, object userToken)
1037 if (address == null)
1038 throw new ArgumentNullException ("address");
1044 async_thread = new Thread (delegate (object state) {
1045 object [] args = (object []) state;
1047 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1048 OnDownloadStringCompleted (
1049 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1050 } catch (ThreadInterruptedException){
1051 OnDownloadStringCompleted (
1052 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1053 } catch (Exception e){
1054 OnDownloadStringCompleted (
1055 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1057 object [] cb_args = new object [] {address, userToken};
1058 async_thread.Start (cb_args);
1064 public void OpenReadAsync (Uri address)
1066 OpenReadAsync (address, null);
1069 public void OpenReadAsync (Uri address, object userToken)
1071 if (address == null)
1072 throw new ArgumentNullException ("address");
1078 async_thread = new Thread (delegate (object state) {
1079 object [] args = (object []) state;
1080 WebRequest request = null;
1082 request = SetupRequest ((Uri) args [0]);
1083 WebResponse response = GetWebResponse (request);
1084 Stream stream = response.GetResponseStream ();
1085 OnOpenReadCompleted (
1086 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1087 } catch (ThreadInterruptedException){
1088 if (request != null)
1091 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1092 } catch (Exception e){
1093 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1095 object [] cb_args = new object [] {address, userToken};
1096 async_thread.Start (cb_args);
1102 public void OpenWriteAsync (Uri address)
1104 OpenWriteAsync (address, null);
1107 public void OpenWriteAsync (Uri address, string method)
1109 OpenWriteAsync (address, method, null);
1112 public void OpenWriteAsync (Uri address, string method, object userToken)
1114 if (address == null)
1115 throw new ArgumentNullException ("address");
1121 async_thread = new Thread (delegate (object state) {
1122 object [] args = (object []) state;
1123 WebRequest request = null;
1125 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1126 Stream stream = request.GetRequestStream ();
1127 OnOpenWriteCompleted (
1128 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1129 } catch (ThreadInterruptedException){
1130 if (request != null)
1132 OnOpenWriteCompleted (
1133 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1134 } catch (Exception e){
1135 OnOpenWriteCompleted (
1136 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1138 object [] cb_args = new object [] {address, method, userToken};
1139 async_thread.Start (cb_args);
1145 public void UploadDataAsync (Uri address, byte [] data)
1147 UploadDataAsync (address, null, data);
1150 public void UploadDataAsync (Uri address, string method, byte [] data)
1152 UploadDataAsync (address, method, data, null);
1155 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1157 if (address == null)
1158 throw new ArgumentNullException ("address");
1160 throw new ArgumentNullException ("data");
1166 async_thread = new Thread (delegate (object state) {
1167 object [] args = (object []) state;
1171 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1173 OnUploadDataCompleted (
1174 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1175 } catch (ThreadInterruptedException){
1176 OnUploadDataCompleted (
1177 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1178 } catch (Exception e){
1179 OnUploadDataCompleted (
1180 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1182 object [] cb_args = new object [] {address, method, data, userToken};
1183 async_thread.Start (cb_args);
1189 public void UploadFileAsync (Uri address, string fileName)
1191 UploadFileAsync (address, null, fileName);
1194 public void UploadFileAsync (Uri address, string method, string fileName)
1196 UploadFileAsync (address, method, fileName, null);
1199 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1201 if (address == null)
1202 throw new ArgumentNullException ("address");
1203 if (fileName == null)
1204 throw new ArgumentNullException ("fileName");
1210 async_thread = new Thread (delegate (object state) {
1211 object [] args = (object []) state;
1215 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1216 OnUploadFileCompleted (
1217 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1218 } catch (ThreadInterruptedException){
1219 OnUploadFileCompleted (
1220 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1221 } catch (Exception e){
1222 OnUploadFileCompleted (
1223 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1225 object [] cb_args = new object [] {address, method, fileName, userToken};
1226 async_thread.Start (cb_args);
1230 // UploadStringAsync
1232 public void UploadStringAsync (Uri address, string data)
1234 UploadStringAsync (address, null, data);
1237 public void UploadStringAsync (Uri address, string method, string data)
1239 UploadStringAsync (address, method, data, null);
1242 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1244 if (address == null)
1245 throw new ArgumentNullException ("address");
1247 throw new ArgumentNullException ("data");
1253 async_thread = new Thread (delegate (object state) {
1254 object [] args = (object []) state;
1257 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1258 OnUploadStringCompleted (
1259 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1260 } catch (ThreadInterruptedException){
1261 OnUploadStringCompleted (
1262 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1263 } catch (Exception e){
1264 OnUploadStringCompleted (
1265 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1267 object [] cb_args = new object [] {address, method, data, userToken};
1268 async_thread.Start (cb_args);
1272 // UploadValuesAsync
1274 public void UploadValuesAsync (Uri address, NameValueCollection values)
1276 UploadValuesAsync (address, null, values);
1279 public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
1281 UploadValuesAsync (address, method, values, null);
1284 public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
1286 if (address == null)
1287 throw new ArgumentNullException ("address");
1289 throw new ArgumentNullException ("values");
1295 async_thread = new Thread (delegate (object state) {
1296 object [] args = (object []) state;
1298 byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1299 OnUploadValuesCompleted (
1300 new UploadValuesCompletedEventArgs (data, null, false, args [3]));
1301 } catch (ThreadInterruptedException){
1302 OnUploadValuesCompleted (
1303 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1304 } catch (Exception e){
1305 OnUploadValuesCompleted (
1306 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1308 object [] cb_args = new object [] {address, method, values, userToken};
1309 async_thread.Start (cb_args);
1313 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
1316 if (DownloadDataCompleted != null)
1317 DownloadDataCompleted (this, args);
1320 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
1323 if (DownloadFileCompleted != null)
1324 DownloadFileCompleted (this, args);
1327 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1329 if (DownloadProgressChanged != null)
1330 DownloadProgressChanged (this, e);
1333 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
1336 if (DownloadStringCompleted != null)
1337 DownloadStringCompleted (this, args);
1340 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
1343 if (OpenReadCompleted != null)
1344 OpenReadCompleted (this, args);
1347 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
1350 if (OpenWriteCompleted != null)
1351 OpenWriteCompleted (this, args);
1354 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
1357 if (UploadDataCompleted != null)
1358 UploadDataCompleted (this, args);
1361 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
1364 if (UploadFileCompleted != null)
1365 UploadFileCompleted (this, args);
1368 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1370 if (UploadProgressChanged != null)
1371 UploadProgressChanged (this, e);
1374 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
1377 if (UploadStringCompleted != null)
1378 UploadStringCompleted (this, args);
1381 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
1384 if (UploadValuesCompleted != null)
1385 UploadValuesCompleted (this, args);
1388 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1390 WebResponse response = request.EndGetResponse (result);
1391 responseHeaders = response.Headers;
1395 protected virtual WebRequest GetWebRequest (Uri address)
1397 return WebRequest.Create (address);
1400 protected virtual WebResponse GetWebResponse (WebRequest request)
1402 WebResponse response = request.GetResponse ();
1403 responseHeaders = response.Headers;