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, 2007 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;
70 using System.Net.Cache;
80 class WebClient : Component
82 static readonly string urlEncodedCType = "application/x-www-form-urlencoded";
83 static byte [] hexBytes;
84 ICredentials credentials;
85 WebHeaderCollection headers;
86 WebHeaderCollection responseHeaders;
89 NameValueCollection queryString;
94 Encoding encoding = Encoding.Default;
101 hexBytes = new byte [16];
103 for (int i = '0'; i <= '9'; i++, index++)
104 hexBytes [index] = (byte) i;
106 for (int i = 'a'; i <= 'f'; i++, index++)
107 hexBytes [index] = (byte) i;
116 public string BaseAddress {
118 if (baseString == null) {
119 if (baseAddress == null)
123 baseString = baseAddress.ToString ();
128 if (value == null || value.Length == 0) {
131 baseAddress = new Uri (value);
137 static Exception GetMustImplement ()
139 return new NotImplementedException ();
143 public RequestCachePolicy CachePolicy
146 throw GetMustImplement ();
149 throw GetMustImplement ();
154 public bool UseDefaultCredentials
157 throw GetMustImplement ();
160 throw GetMustImplement ();
165 public ICredentials Credentials {
166 get { return credentials; }
167 set { credentials = value; }
170 public WebHeaderCollection Headers {
173 headers = new WebHeaderCollection ();
177 set { headers = value; }
180 public NameValueCollection QueryString {
182 if (queryString == null)
183 queryString = new NameValueCollection ();
187 set { queryString = value; }
190 public WebHeaderCollection ResponseHeaders {
191 get { return responseHeaders; }
195 public Encoding Encoding {
196 get { return encoding; }
199 throw new ArgumentNullException ("Encoding");
204 public IWebProxy Proxy {
205 get { return proxy; }
206 set { proxy = value; }
212 get { return is_busy; }
216 get { return is_busy; }
225 throw new NotSupportedException ("WebClient does not support conccurent I/O operations.");
238 public byte [] DownloadData (string address)
242 throw new ArgumentNullException ("address");
245 return DownloadData (CreateUri (address));
251 byte [] DownloadData (Uri address)
255 throw new ArgumentNullException ("address");
263 return DownloadDataCore (address, null);
269 byte [] DownloadDataCore (Uri address, object userToken)
271 WebRequest request = null;
274 request = SetupRequest (address);
275 WebResponse response = GetWebResponse (request);
276 Stream st = response.GetResponseStream ();
277 return ReadAll (st, (int) response.ContentLength, userToken);
278 } catch (ThreadInterruptedException){
282 } catch (WebException wexc) {
284 } catch (Exception ex) {
285 throw new WebException ("An error occurred " +
286 "performing a WebClient request.", ex);
292 public void DownloadFile (string address, string fileName)
296 throw new ArgumentNullException ("address");
299 DownloadFile (CreateUri (address), fileName);
305 void DownloadFile (Uri address, string fileName)
309 throw new ArgumentNullException ("address");
310 if (fileName == null)
311 throw new ArgumentNullException ("fileName");
319 DownloadFileCore (address, fileName, null);
320 } catch (WebException wexc) {
322 } catch (Exception ex) {
323 throw new WebException ("An error occurred " +
324 "performing a WebClient request.", ex);
330 void DownloadFileCore (Uri address, string fileName, object userToken)
332 WebRequest request = null;
334 using (FileStream f = new FileStream (fileName, FileMode.Create)) {
336 request = SetupRequest (address);
337 WebResponse response = GetWebResponse (request);
338 Stream st = response.GetResponseStream ();
340 int cLength = (int) response.ContentLength;
341 int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
342 byte [] buffer = new byte [length];
346 long notify_total = 0;
348 while ((nread = st.Read (buffer, 0, length)) != 0){
351 notify_total += nread;
352 OnDownloadProgressChanged (
353 new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
357 f.Write (buffer, 0, nread);
359 } catch (ThreadInterruptedException){
369 public Stream OpenRead (string address)
373 throw new ArgumentNullException ("address");
376 return OpenRead (CreateUri (address));
382 Stream OpenRead (Uri address)
386 throw new ArgumentNullException ("address");
389 WebRequest request = null;
395 request = SetupRequest (address);
396 WebResponse response = GetWebResponse (request);
397 return response.GetResponseStream ();
398 } catch (WebException wexc) {
400 } catch (Exception ex) {
401 throw new WebException ("An error occurred " +
402 "performing a WebClient request.", ex);
410 public Stream OpenWrite (string address)
414 throw new ArgumentNullException ("address");
417 return OpenWrite (CreateUri (address));
420 public Stream OpenWrite (string address, string method)
424 throw new ArgumentNullException ("address");
427 return OpenWrite (CreateUri (address), method);
433 Stream OpenWrite (Uri address)
435 return OpenWrite (address, (string) null);
441 Stream OpenWrite (Uri address, string method)
445 throw new ArgumentNullException ("address");
453 WebRequest request = SetupRequest (address, method, true);
454 return request.GetRequestStream ();
455 } catch (WebException wexc) {
457 } catch (Exception ex) {
458 throw new WebException ("An error occurred " +
459 "performing a WebClient request.", ex);
465 private string DetermineMethod (Uri address, string method, bool is_upload)
471 if (address.Scheme == Uri.UriSchemeFtp)
472 return (is_upload) ? "STOR" : "RETR";
474 return (is_upload) ? "POST" : "GET";
479 public byte [] UploadData (string address, byte [] data)
483 throw new ArgumentNullException ("address");
486 return UploadData (CreateUri (address), data);
489 public byte [] UploadData (string address, string method, byte [] data)
493 throw new ArgumentNullException ("address");
496 return UploadData (CreateUri (address), method, data);
502 byte [] UploadData (Uri address, byte [] data)
504 return UploadData (address, (string) null, data);
510 byte [] UploadData (Uri address, string method, byte [] data)
514 throw new ArgumentNullException ("address");
516 throw new ArgumentNullException ("data");
524 return UploadDataCore (address, method, data, null);
525 } catch (WebException) {
527 } catch (Exception ex) {
528 throw new WebException ("An error occurred " +
529 "performing a WebClient request.", ex);
535 byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
539 throw new ArgumentNullException ("address");
541 throw new ArgumentNullException ("data");
544 WebRequest request = SetupRequest (address, method, true);
546 int contentLength = data.Length;
547 request.ContentLength = contentLength;
548 using (Stream stream = request.GetRequestStream ()) {
549 stream.Write (data, 0, contentLength);
552 WebResponse response = GetWebResponse (request);
553 Stream st = response.GetResponseStream ();
554 return ReadAll (st, (int) response.ContentLength, userToken);
555 } catch (ThreadInterruptedException){
564 public byte [] UploadFile (string address, string fileName)
568 throw new ArgumentNullException ("address");
571 return UploadFile (CreateUri (address), fileName);
577 byte [] UploadFile (Uri address, string fileName)
579 return UploadFile (address, (string) null, fileName);
582 public byte [] UploadFile (string address, string method, string fileName)
584 return UploadFile (CreateUri (address), method, fileName);
590 byte [] UploadFile (Uri address, string method, string fileName)
594 throw new ArgumentNullException ("address");
595 if (fileName == null)
596 throw new ArgumentNullException ("fileName");
604 return UploadFileCore (address, method, fileName, null);
605 } catch (WebException wexc) {
607 } catch (Exception ex) {
608 throw new WebException ("An error occurred " +
609 "performing a WebClient request.", ex);
615 byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
619 throw new ArgumentNullException ("address");
622 string fileCType = Headers ["Content-Type"];
623 if (fileCType != null) {
624 string lower = fileCType.ToLower ();
625 if (lower.StartsWith ("multipart/"))
626 throw new WebException ("Content-Type cannot be set to a multipart" +
627 " type for this request.");
629 fileCType = "application/octet-stream";
632 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
633 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
634 Stream reqStream = null;
635 Stream fStream = null;
636 byte [] resultBytes = null;
638 fileName = Path.GetFullPath (fileName);
640 WebRequest request = null;
642 fStream = File.OpenRead (fileName);
643 request = SetupRequest (address, method, true);
644 reqStream = request.GetRequestStream ();
645 byte [] realBoundary = Encoding.ASCII.GetBytes ("--" + boundary + "\r\n");
646 reqStream.Write (realBoundary, 0, realBoundary.Length);
647 string partHeaders = String.Format ("Content-Disposition: form-data; " +
648 "name=\"file\"; filename=\"{0}\"\r\n" +
649 "Content-Type: {1}\r\n\r\n",
650 Path.GetFileName (fileName), fileCType);
652 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
653 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
655 byte [] buffer = new byte [4096];
656 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
657 reqStream.Write (buffer, 0, nread);
659 reqStream.WriteByte ((byte) '\r');
660 reqStream.WriteByte ((byte) '\n');
661 reqStream.Write (realBoundary, 0, realBoundary.Length);
664 WebResponse response = GetWebResponse (request);
665 Stream st = response.GetResponseStream ();
666 resultBytes = ReadAll (st, (int) response.ContentLength, userToken);
667 } catch (ThreadInterruptedException){
675 if (reqStream != null)
682 public byte[] UploadValues (string address, NameValueCollection data)
686 throw new ArgumentNullException ("address");
689 return UploadValues (CreateUri (address), data);
692 public byte[] UploadValues (string address, string method, NameValueCollection data)
696 throw new ArgumentNullException ("address");
699 return UploadValues (CreateUri (address), method, data);
705 byte[] UploadValues (Uri address, NameValueCollection data)
707 return UploadValues (address, (string) null, data);
713 byte[] UploadValues (Uri address, string method, NameValueCollection data)
717 throw new ArgumentNullException ("address");
719 throw new ArgumentNullException ("data");
727 return UploadValuesCore (address, method, data, null);
728 } catch (WebException wexc) {
730 } catch (Exception ex) {
731 throw new WebException ("An error occurred " +
732 "performing a WebClient request.", ex);
738 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
742 throw new ArgumentNullException ("data");
745 string cType = Headers ["Content-Type"];
746 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
747 throw new WebException ("Content-Type header cannot be changed from its default " +
748 "value for this request.");
750 Headers ["Content-Type"] = urlEncodedCType;
751 WebRequest request = SetupRequest (uri, method, true);
753 MemoryStream tmpStream = new MemoryStream ();
754 foreach (string key in data) {
755 byte [] bytes = Encoding.UTF8.GetBytes (key);
756 UrlEncodeAndWrite (tmpStream, bytes);
757 tmpStream.WriteByte ((byte) '=');
758 bytes = Encoding.UTF8.GetBytes (data [key]);
759 UrlEncodeAndWrite (tmpStream, bytes);
760 tmpStream.WriteByte ((byte) '&');
763 int length = (int) tmpStream.Length;
765 tmpStream.SetLength (--length); // remove trailing '&'
767 byte [] buf = tmpStream.GetBuffer ();
768 request.ContentLength = length;
769 using (Stream rqStream = request.GetRequestStream ()) {
770 rqStream.Write (buf, 0, length);
774 WebResponse response = GetWebResponse (request);
775 Stream st = response.GetResponseStream ();
776 return ReadAll (st, (int) response.ContentLength, userToken);
777 } catch (ThreadInterruptedException) {
784 public string DownloadString (string address)
787 throw new ArgumentNullException ("address");
789 return encoding.GetString (DownloadData (CreateUri (address)));
792 public string DownloadString (Uri address)
795 throw new ArgumentNullException ("address");
797 return encoding.GetString (DownloadData (CreateUri (address)));
800 public string UploadString (string address, string data)
803 throw new ArgumentNullException ("address");
805 throw new ArgumentNullException ("data");
807 byte [] resp = UploadData (address, encoding.GetBytes (data));
808 return encoding.GetString (resp);
811 public string UploadString (string address, string method, string data)
814 throw new ArgumentNullException ("address");
816 throw new ArgumentNullException ("data");
818 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
819 return encoding.GetString (resp);
822 public string UploadString (Uri address, string data)
825 throw new ArgumentNullException ("address");
827 throw new ArgumentNullException ("data");
829 byte [] resp = UploadData (address, encoding.GetBytes (data));
830 return encoding.GetString (resp);
833 public string UploadString (Uri address, string method, string data)
836 throw new ArgumentNullException ("address");
838 throw new ArgumentNullException ("data");
840 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
841 return encoding.GetString (resp);
844 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
845 public event AsyncCompletedEventHandler DownloadFileCompleted;
846 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
847 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
848 public event OpenReadCompletedEventHandler OpenReadCompleted;
849 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
850 public event UploadDataCompletedEventHandler UploadDataCompleted;
851 public event UploadFileCompletedEventHandler UploadFileCompleted;
852 public event UploadProgressChangedEventHandler UploadProgressChanged;
853 public event UploadStringCompletedEventHandler UploadStringCompleted;
854 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
857 Uri CreateUri (string address)
861 return MakeUri (address);
862 } catch (Exception ex) {
863 throw new WebException ("An error occurred " +
864 "performing a WebClient request.", ex);
867 return MakeUri (address);
872 Uri CreateUri (Uri address)
874 string query = address.Query;
875 if (String.IsNullOrEmpty (query))
876 query = GetQueryString (true);
878 if (baseAddress == null && query == null)
881 if (baseAddress == null)
882 return new Uri (address.ToString () + query, (query != null));
885 return new Uri (baseAddress, address.ToString ());
887 return new Uri (baseAddress, address.ToString () + query, (query != null));
892 string GetQueryString (bool add_qmark)
894 if (queryString == null || queryString.Count == 0)
897 StringBuilder sb = new StringBuilder ();
901 foreach (string key in queryString)
902 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
905 sb.Length--; // removes last '&' or the '?' if empty.
910 return sb.ToString ();
913 Uri MakeUri (string path)
915 string query = GetQueryString (true);
916 if (baseAddress == null && query == null) {
918 return new Uri (path);
920 } catch (ArgumentNullException) {
921 path = Path.GetFullPath (path);
922 return new Uri ("file://" + path);
924 } catch (UriFormatException) {
925 path = Path.GetFullPath (path);
926 return new Uri ("file://" + path);
930 if (baseAddress == null)
931 return new Uri (path + query, (query != null));
934 return new Uri (baseAddress, path);
936 return new Uri (baseAddress, path + query, (query != null));
939 WebRequest SetupRequest (Uri uri)
941 WebRequest request = WebRequest.Create (uri);
944 request.Proxy = Proxy;
946 request.Credentials = credentials;
948 // Special headers. These are properties of HttpWebRequest.
949 // What do we do with other requests differnt from HttpWebRequest?
950 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
951 HttpWebRequest req = (HttpWebRequest) request;
952 string expect = headers ["Expect"];
953 string contentType = headers ["Content-Type"];
954 string accept = headers ["Accept"];
955 string connection = headers ["Connection"];
956 string userAgent = headers ["User-Agent"];
957 string referer = headers ["Referer"];
958 headers.RemoveInternal ("Expect");
959 headers.RemoveInternal ("Content-Type");
960 headers.RemoveInternal ("Accept");
961 headers.RemoveInternal ("Connection");
962 headers.RemoveInternal ("Referer");
963 headers.RemoveInternal ("User-Agent");
964 request.Headers = headers;
966 if (expect != null && expect.Length > 0)
969 if (accept != null && accept.Length > 0)
972 if (contentType != null && contentType.Length > 0)
973 req.ContentType = contentType;
975 if (connection != null && connection.Length > 0)
976 req.Connection = connection;
978 if (userAgent != null && userAgent.Length > 0)
979 req.UserAgent = userAgent;
981 if (referer != null && referer.Length > 0)
982 req.Referer = referer;
985 responseHeaders = null;
989 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
991 WebRequest request = SetupRequest (uri);
992 request.Method = DetermineMethod (uri, method, is_upload);
996 byte [] ReadAll (Stream stream, int length, object userToken)
998 MemoryStream ms = null;
1000 bool nolength = (length == -1);
1001 int size = ((nolength) ? 8192 : length);
1003 ms = new MemoryStream ();
1008 byte [] buffer = new byte [size];
1009 while ((nread = stream.Read (buffer, offset, size)) != 0) {
1011 ms.Write (buffer, 0, nread);
1019 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
1025 return ms.ToArray ();
1030 string UrlEncode (string str)
1032 StringBuilder result = new StringBuilder ();
1034 int len = str.Length;
1035 for (int i = 0; i < len; i++) {
1038 result.Append ('+');
1039 else if ((c < '0' && c != '-' && c != '.') ||
1040 (c < 'A' && c > '9') ||
1041 (c > 'Z' && c < 'a' && c != '_') ||
1043 result.Append ('%');
1044 int idx = ((int) c) >> 4;
1045 result.Append ((char) hexBytes [idx]);
1046 idx = ((int) c) & 0x0F;
1047 result.Append ((char) hexBytes [idx]);
1053 return result.ToString ();
1056 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
1061 int len = bytes.Length;
1065 for (int i = 0; i < len; i++) {
1066 char c = (char) bytes [i];
1068 stream.WriteByte ((byte) '+');
1069 else if ((c < '0' && c != '-' && c != '.') ||
1070 (c < 'A' && c > '9') ||
1071 (c > 'Z' && c < 'a' && c != '_') ||
1073 stream.WriteByte ((byte) '%');
1074 int idx = ((int) c) >> 4;
1075 stream.WriteByte (hexBytes [idx]);
1076 idx = ((int) c) & 0x0F;
1077 stream.WriteByte (hexBytes [idx]);
1079 stream.WriteByte ((byte) c);
1085 public void CancelAsync ()
1088 if (async_thread == null)
1092 // We first flag things as done, in case the Interrupt hangs
1093 // or the thread decides to hang in some other way inside the
1094 // event handlers, or if we are stuck somewhere else. This
1095 // ensures that the WebClient object is reusable immediately
1097 Thread t = async_thread;
1103 void CompleteAsync ()
1107 async_thread = null;
1111 // DownloadDataAsync
1113 public void DownloadDataAsync (Uri address)
1115 DownloadDataAsync (address, null);
1118 public void DownloadDataAsync (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;
1130 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
1131 OnDownloadDataCompleted (
1132 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
1133 } catch (ThreadInterruptedException){
1134 OnDownloadDataCompleted (
1135 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
1137 } catch (Exception e){
1138 OnDownloadDataCompleted (
1139 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
1142 object [] cb_args = new object [] {address, userToken};
1143 async_thread.Start (cb_args);
1147 // DownloadFileAsync
1149 public void DownloadFileAsync (Uri address, string fileName)
1151 DownloadFileAsync (address, fileName, null);
1154 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1156 if (address == null)
1157 throw new ArgumentNullException ("address");
1158 if (fileName == null)
1159 throw new ArgumentNullException ("fileName");
1165 async_thread = new Thread (delegate (object state) {
1166 object [] args = (object []) state;
1168 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1169 OnDownloadFileCompleted (
1170 new AsyncCompletedEventArgs (null, false, args [2]));
1171 } catch (ThreadInterruptedException){
1172 OnDownloadFileCompleted (
1173 new AsyncCompletedEventArgs (null, true, args [2]));
1174 } catch (Exception e){
1175 OnDownloadFileCompleted (
1176 new AsyncCompletedEventArgs (e, false, args [2]));
1178 object [] cb_args = new object [] {address, fileName, userToken};
1179 async_thread.Start (cb_args);
1183 // DownloadStringAsync
1185 public void DownloadStringAsync (Uri address)
1187 DownloadStringAsync (address, null);
1190 public void DownloadStringAsync (Uri address, object userToken)
1192 if (address == null)
1193 throw new ArgumentNullException ("address");
1199 async_thread = new Thread (delegate (object state) {
1200 object [] args = (object []) state;
1202 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1203 OnDownloadStringCompleted (
1204 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1205 } catch (ThreadInterruptedException){
1206 OnDownloadStringCompleted (
1207 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1208 } catch (Exception e){
1209 OnDownloadStringCompleted (
1210 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1212 object [] cb_args = new object [] {address, userToken};
1213 async_thread.Start (cb_args);
1219 public void OpenReadAsync (Uri address)
1221 OpenReadAsync (address, null);
1224 public void OpenReadAsync (Uri address, object userToken)
1226 if (address == null)
1227 throw new ArgumentNullException ("address");
1233 async_thread = new Thread (delegate (object state) {
1234 object [] args = (object []) state;
1235 WebRequest request = null;
1237 request = SetupRequest ((Uri) args [0]);
1238 WebResponse response = GetWebResponse (request);
1239 Stream stream = response.GetResponseStream ();
1240 OnOpenReadCompleted (
1241 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1242 } catch (ThreadInterruptedException){
1243 if (request != null)
1246 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1247 } catch (Exception e){
1248 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1250 object [] cb_args = new object [] {address, userToken};
1251 async_thread.Start (cb_args);
1257 public void OpenWriteAsync (Uri address)
1259 OpenWriteAsync (address, null);
1262 public void OpenWriteAsync (Uri address, string method)
1264 OpenWriteAsync (address, method, null);
1267 public void OpenWriteAsync (Uri address, string method, object userToken)
1269 if (address == null)
1270 throw new ArgumentNullException ("address");
1276 async_thread = new Thread (delegate (object state) {
1277 object [] args = (object []) state;
1278 WebRequest request = null;
1280 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1281 Stream stream = request.GetRequestStream ();
1282 OnOpenWriteCompleted (
1283 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1284 } catch (ThreadInterruptedException){
1285 if (request != null)
1287 OnOpenWriteCompleted (
1288 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1289 } catch (Exception e){
1290 OnOpenWriteCompleted (
1291 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1293 object [] cb_args = new object [] {address, method, userToken};
1294 async_thread.Start (cb_args);
1300 public void UploadDataAsync (Uri address, byte [] data)
1302 UploadDataAsync (address, null, data);
1305 public void UploadDataAsync (Uri address, string method, byte [] data)
1307 UploadDataAsync (address, method, data, null);
1310 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1312 if (address == null)
1313 throw new ArgumentNullException ("address");
1315 throw new ArgumentNullException ("data");
1321 async_thread = new Thread (delegate (object state) {
1322 object [] args = (object []) state;
1326 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1328 OnUploadDataCompleted (
1329 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1330 } catch (ThreadInterruptedException){
1331 OnUploadDataCompleted (
1332 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1333 } catch (Exception e){
1334 OnUploadDataCompleted (
1335 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1337 object [] cb_args = new object [] {address, method, data, userToken};
1338 async_thread.Start (cb_args);
1344 public void UploadFileAsync (Uri address, string fileName)
1346 UploadFileAsync (address, null, fileName);
1349 public void UploadFileAsync (Uri address, string method, string fileName)
1351 UploadFileAsync (address, method, fileName, null);
1354 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1356 if (address == null)
1357 throw new ArgumentNullException ("address");
1358 if (fileName == null)
1359 throw new ArgumentNullException ("fileName");
1365 async_thread = new Thread (delegate (object state) {
1366 object [] args = (object []) state;
1370 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1371 OnUploadFileCompleted (
1372 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1373 } catch (ThreadInterruptedException){
1374 OnUploadFileCompleted (
1375 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1376 } catch (Exception e){
1377 OnUploadFileCompleted (
1378 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1380 object [] cb_args = new object [] {address, method, fileName, userToken};
1381 async_thread.Start (cb_args);
1385 // UploadStringAsync
1387 public void UploadStringAsync (Uri address, string data)
1389 UploadStringAsync (address, null, data);
1392 public void UploadStringAsync (Uri address, string method, string data)
1394 UploadStringAsync (address, method, data, null);
1397 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1399 if (address == null)
1400 throw new ArgumentNullException ("address");
1402 throw new ArgumentNullException ("data");
1408 async_thread = new Thread (delegate (object state) {
1409 object [] args = (object []) state;
1412 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1413 OnUploadStringCompleted (
1414 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1415 } catch (ThreadInterruptedException){
1416 OnUploadStringCompleted (
1417 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1418 } catch (Exception e){
1419 OnUploadStringCompleted (
1420 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1422 object [] cb_args = new object [] {address, method, data, userToken};
1423 async_thread.Start (cb_args);
1427 // UploadValuesAsync
1429 public void UploadValuesAsync (Uri address, NameValueCollection values)
1431 UploadValuesAsync (address, null, values);
1434 public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
1436 UploadValuesAsync (address, method, values, null);
1439 public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
1441 if (address == null)
1442 throw new ArgumentNullException ("address");
1444 throw new ArgumentNullException ("values");
1450 async_thread = new Thread (delegate (object state) {
1451 object [] args = (object []) state;
1453 byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1454 OnUploadValuesCompleted (
1455 new UploadValuesCompletedEventArgs (data, null, false, args [3]));
1456 } catch (ThreadInterruptedException){
1457 OnUploadValuesCompleted (
1458 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1459 } catch (Exception e){
1460 OnUploadValuesCompleted (
1461 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1463 object [] cb_args = new object [] {address, method, values, userToken};
1464 async_thread.Start (cb_args);
1468 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
1471 if (DownloadDataCompleted != null)
1472 DownloadDataCompleted (this, args);
1475 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
1478 if (DownloadFileCompleted != null)
1479 DownloadFileCompleted (this, args);
1482 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1484 if (DownloadProgressChanged != null)
1485 DownloadProgressChanged (this, e);
1488 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
1491 if (DownloadStringCompleted != null)
1492 DownloadStringCompleted (this, args);
1495 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
1498 if (OpenReadCompleted != null)
1499 OpenReadCompleted (this, args);
1502 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
1505 if (OpenWriteCompleted != null)
1506 OpenWriteCompleted (this, args);
1509 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
1512 if (UploadDataCompleted != null)
1513 UploadDataCompleted (this, args);
1516 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
1519 if (UploadFileCompleted != null)
1520 UploadFileCompleted (this, args);
1523 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1525 if (UploadProgressChanged != null)
1526 UploadProgressChanged (this, e);
1529 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
1532 if (UploadStringCompleted != null)
1533 UploadStringCompleted (this, args);
1536 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
1539 if (UploadValuesCompleted != null)
1540 UploadValuesCompleted (this, args);
1543 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1545 WebResponse response = request.EndGetResponse (result);
1546 responseHeaders = response.Headers;
1554 WebRequest GetWebRequest (Uri address)
1556 return SetupRequest (address);
1562 WebResponse GetWebResponse (WebRequest request)
1564 WebResponse response = request.GetResponse ();
1565 responseHeaders = response.Headers;