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 WebResponse response = GetWebResponse (request);
248 Stream st = response.GetResponseStream ();
249 return ReadAll (st, (int) response.ContentLength, userToken);
250 } catch (ThreadInterruptedException){
254 } catch (WebException) {
256 } catch (Exception ex) {
257 throw new WebException ("An error occurred " +
258 "performing a WebClient request.", ex);
264 public void DownloadFile (string address, string fileName)
267 throw new ArgumentNullException ("address");
269 DownloadFile (CreateUri (address), fileName);
272 public void DownloadFile (Uri address, string fileName)
275 throw new ArgumentNullException ("address");
276 if (fileName == null)
277 throw new ArgumentNullException ("fileName");
282 DownloadFileCore (address, fileName, null);
283 } catch (WebException) {
285 } catch (Exception ex) {
286 throw new WebException ("An error occurred " +
287 "performing a WebClient request.", ex);
293 void DownloadFileCore (Uri address, string fileName, object userToken)
295 WebRequest request = null;
297 using (FileStream f = new FileStream (fileName, FileMode.Create)) {
299 request = SetupRequest (address);
300 WebResponse response = GetWebResponse (request);
301 Stream st = response.GetResponseStream ();
303 int cLength = (int) response.ContentLength;
304 int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
305 byte [] buffer = new byte [length];
308 long notify_total = 0;
309 while ((nread = st.Read (buffer, 0, length)) != 0){
311 notify_total += nread;
312 OnDownloadProgressChanged (
313 new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
316 f.Write (buffer, 0, nread);
318 } catch (ThreadInterruptedException){
328 public Stream OpenRead (string address)
331 throw new ArgumentNullException ("address");
332 return OpenRead (CreateUri (address));
335 public Stream OpenRead (Uri address)
338 throw new ArgumentNullException ("address");
340 WebRequest request = null;
344 request = SetupRequest (address);
345 WebResponse response = GetWebResponse (request);
346 return response.GetResponseStream ();
347 } catch (WebException) {
349 } catch (Exception ex) {
350 throw new WebException ("An error occurred " +
351 "performing a WebClient request.", ex);
359 public Stream OpenWrite (string address)
362 throw new ArgumentNullException ("address");
364 return OpenWrite (CreateUri (address));
367 public Stream OpenWrite (string address, string method)
370 throw new ArgumentNullException ("address");
372 return OpenWrite (CreateUri (address), method);
375 public Stream OpenWrite (Uri address)
377 return OpenWrite (address, (string) null);
380 public Stream OpenWrite (Uri address, string method)
383 throw new ArgumentNullException ("address");
388 WebRequest request = SetupRequest (address, method, true);
389 return request.GetRequestStream ();
390 } catch (WebException) {
392 } catch (Exception ex) {
393 throw new WebException ("An error occurred " +
394 "performing a WebClient request.", ex);
400 private string DetermineMethod (Uri address, string method, bool is_upload)
405 if (address.Scheme == Uri.UriSchemeFtp)
406 return (is_upload) ? "STOR" : "RETR";
408 return (is_upload) ? "POST" : "GET";
413 public byte [] UploadData (string address, byte [] data)
416 throw new ArgumentNullException ("address");
418 return UploadData (CreateUri (address), data);
421 public byte [] UploadData (string address, string method, byte [] data)
424 throw new ArgumentNullException ("address");
426 return UploadData (CreateUri (address), method, data);
429 public byte [] UploadData (Uri address, byte [] data)
431 return UploadData (address, (string) null, data);
434 public byte [] UploadData (Uri address, string method, byte [] data)
437 throw new ArgumentNullException ("address");
439 throw new ArgumentNullException ("data");
444 return UploadDataCore (address, method, data, null);
445 } catch (WebException) {
447 } catch (Exception ex) {
448 throw new WebException ("An error occurred " +
449 "performing a WebClient request.", ex);
455 byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
457 WebRequest request = SetupRequest (address, method, true);
459 int contentLength = data.Length;
460 request.ContentLength = contentLength;
461 using (Stream stream = request.GetRequestStream ()) {
462 stream.Write (data, 0, contentLength);
465 WebResponse response = GetWebResponse (request);
466 Stream st = response.GetResponseStream ();
467 return ReadAll (st, (int) response.ContentLength, userToken);
468 } catch (ThreadInterruptedException){
477 public byte [] UploadFile (string address, string fileName)
480 throw new ArgumentNullException ("address");
482 return UploadFile (CreateUri (address), fileName);
485 public byte [] UploadFile (Uri address, string fileName)
487 return UploadFile (address, (string) null, fileName);
490 public byte [] UploadFile (string address, string method, string fileName)
492 return UploadFile (CreateUri (address), method, fileName);
495 public byte [] UploadFile (Uri address, string method, string fileName)
498 throw new ArgumentNullException ("address");
499 if (fileName == null)
500 throw new ArgumentNullException ("fileName");
505 return UploadFileCore (address, method, fileName, null);
506 } catch (WebException) {
508 } catch (Exception ex) {
509 throw new WebException ("An error occurred " +
510 "performing a WebClient request.", ex);
516 byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
518 string fileCType = Headers ["Content-Type"];
519 if (fileCType != null) {
520 string lower = fileCType.ToLower ();
521 if (lower.StartsWith ("multipart/"))
522 throw new WebException ("Content-Type cannot be set to a multipart" +
523 " type for this request.");
525 fileCType = "application/octet-stream";
528 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
529 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
530 Stream reqStream = null;
531 Stream fStream = null;
532 byte [] resultBytes = null;
534 fileName = Path.GetFullPath (fileName);
536 WebRequest request = null;
538 fStream = File.OpenRead (fileName);
539 request = SetupRequest (address, method, true);
540 reqStream = request.GetRequestStream ();
541 byte [] realBoundary = Encoding.ASCII.GetBytes ("--" + boundary + "\r\n");
542 reqStream.Write (realBoundary, 0, realBoundary.Length);
543 string partHeaders = String.Format ("Content-Disposition: form-data; " +
544 "name=\"file\"; filename=\"{0}\"\r\n" +
545 "Content-Type: {1}\r\n\r\n",
546 Path.GetFileName (fileName), fileCType);
548 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
549 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
551 byte [] buffer = new byte [4096];
552 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
553 reqStream.Write (buffer, 0, nread);
555 reqStream.WriteByte ((byte) '\r');
556 reqStream.WriteByte ((byte) '\n');
557 reqStream.Write (realBoundary, 0, realBoundary.Length);
560 WebResponse response = GetWebResponse (request);
561 Stream st = response.GetResponseStream ();
562 resultBytes = ReadAll (st, (int) response.ContentLength, userToken);
563 } catch (ThreadInterruptedException){
571 if (reqStream != null)
578 public byte[] UploadValues (string address, NameValueCollection data)
581 throw new ArgumentNullException ("address");
583 return UploadValues (CreateUri (address), data);
586 public byte[] UploadValues (string address, string method, NameValueCollection data)
589 throw new ArgumentNullException ("address");
590 return UploadValues (CreateUri (address), method, data);
593 public byte[] UploadValues (Uri address, NameValueCollection data)
595 return UploadValues (address, (string) null, data);
598 public byte[] UploadValues (Uri address, string method, NameValueCollection data)
601 throw new ArgumentNullException ("address");
603 throw new ArgumentNullException ("data");
608 return UploadValuesCore (address, method, data, null);
609 } catch (WebException) {
611 } catch (Exception ex) {
612 throw new WebException ("An error occurred " +
613 "performing a WebClient request.", ex);
619 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
621 string cType = Headers ["Content-Type"];
622 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
623 throw new WebException ("Content-Type header cannot be changed from its default " +
624 "value for this request.");
626 Headers ["Content-Type"] = urlEncodedCType;
627 WebRequest request = SetupRequest (uri, method, true);
629 MemoryStream tmpStream = new MemoryStream ();
630 foreach (string key in data) {
631 byte [] bytes = Encoding.UTF8.GetBytes (key);
632 UrlEncodeAndWrite (tmpStream, bytes);
633 tmpStream.WriteByte ((byte) '=');
634 bytes = Encoding.UTF8.GetBytes (data [key]);
635 UrlEncodeAndWrite (tmpStream, bytes);
636 tmpStream.WriteByte ((byte) '&');
639 int length = (int) tmpStream.Length;
641 tmpStream.SetLength (--length); // remove trailing '&'
643 byte [] buf = tmpStream.GetBuffer ();
644 request.ContentLength = length;
645 using (Stream rqStream = request.GetRequestStream ()) {
646 rqStream.Write (buf, 0, length);
650 WebResponse response = GetWebResponse (request);
651 Stream st = response.GetResponseStream ();
652 return ReadAll (st, (int) response.ContentLength, userToken);
653 } catch (ThreadInterruptedException) {
659 public string DownloadString (string address)
662 throw new ArgumentNullException ("address");
664 return encoding.GetString (DownloadData (CreateUri (address)));
667 public string DownloadString (Uri address)
670 throw new ArgumentNullException ("address");
672 return encoding.GetString (DownloadData (CreateUri (address)));
675 public string UploadString (string address, string data)
678 throw new ArgumentNullException ("address");
680 throw new ArgumentNullException ("data");
682 byte [] resp = UploadData (address, encoding.GetBytes (data));
683 return encoding.GetString (resp);
686 public string UploadString (string address, string method, string data)
689 throw new ArgumentNullException ("address");
691 throw new ArgumentNullException ("data");
693 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
694 return encoding.GetString (resp);
697 public string UploadString (Uri address, string data)
700 throw new ArgumentNullException ("address");
702 throw new ArgumentNullException ("data");
704 byte [] resp = UploadData (address, encoding.GetBytes (data));
705 return encoding.GetString (resp);
708 public string UploadString (Uri address, string method, string data)
711 throw new ArgumentNullException ("address");
713 throw new ArgumentNullException ("data");
715 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
716 return encoding.GetString (resp);
719 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
720 public event AsyncCompletedEventHandler DownloadFileCompleted;
721 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
722 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
723 public event OpenReadCompletedEventHandler OpenReadCompleted;
724 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
725 public event UploadDataCompletedEventHandler UploadDataCompleted;
726 public event UploadFileCompletedEventHandler UploadFileCompleted;
727 public event UploadProgressChangedEventHandler UploadProgressChanged;
728 public event UploadStringCompletedEventHandler UploadStringCompleted;
729 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
731 Uri CreateUri (string address)
735 if (baseAddress == null)
736 uri = new Uri (address);
738 uri = new Uri (baseAddress, address);
739 return CreateUri (uri);
742 return new Uri (Path.GetFullPath (address));
745 Uri CreateUri (Uri address)
747 Uri result = address;
748 if (baseAddress != null && !result.IsAbsoluteUri) {
750 result = new Uri (baseAddress, result.OriginalString);
752 return result; // Not much we can do here.
756 string query = result.Query;
757 if (String.IsNullOrEmpty (query))
758 query = GetQueryString (true);
759 UriBuilder builder = new UriBuilder (address);
760 if (!String.IsNullOrEmpty (query))
761 builder.Query = query.Substring (1);
765 string GetQueryString (bool add_qmark)
767 if (queryString == null || queryString.Count == 0)
770 StringBuilder sb = new StringBuilder ();
774 foreach (string key in queryString)
775 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
778 sb.Length--; // removes last '&' or the '?' if empty.
783 return sb.ToString ();
786 WebRequest SetupRequest (Uri uri)
788 WebRequest request = GetWebRequest (uri);
790 request.Proxy = Proxy;
791 request.Credentials = credentials;
793 // Special headers. These are properties of HttpWebRequest.
794 // What do we do with other requests differnt from HttpWebRequest?
795 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
796 HttpWebRequest req = (HttpWebRequest) request;
797 string expect = headers ["Expect"];
798 string contentType = headers ["Content-Type"];
799 string accept = headers ["Accept"];
800 string connection = headers ["Connection"];
801 string userAgent = headers ["User-Agent"];
802 string referer = headers ["Referer"];
803 headers.RemoveInternal ("Expect");
804 headers.RemoveInternal ("Content-Type");
805 headers.RemoveInternal ("Accept");
806 headers.RemoveInternal ("Connection");
807 headers.RemoveInternal ("Referer");
808 headers.RemoveInternal ("User-Agent");
809 request.Headers = headers;
811 if (expect != null && expect.Length > 0)
814 if (accept != null && accept.Length > 0)
817 if (contentType != null && contentType.Length > 0)
818 req.ContentType = contentType;
820 if (connection != null && connection.Length > 0)
821 req.Connection = connection;
823 if (userAgent != null && userAgent.Length > 0)
824 req.UserAgent = userAgent;
826 if (referer != null && referer.Length > 0)
827 req.Referer = referer;
830 responseHeaders = null;
834 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
836 WebRequest request = SetupRequest (uri);
837 request.Method = DetermineMethod (uri, method, is_upload);
841 byte [] ReadAll (Stream stream, int length, object userToken)
843 MemoryStream ms = null;
845 bool nolength = (length == -1);
846 int size = ((nolength) ? 8192 : length);
848 ms = new MemoryStream ();
853 byte [] buffer = new byte [size];
854 while ((nread = stream.Read (buffer, offset, size)) != 0) {
856 ms.Write (buffer, 0, nread);
863 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
868 return ms.ToArray ();
873 string UrlEncode (string str)
875 StringBuilder result = new StringBuilder ();
877 int len = str.Length;
878 for (int i = 0; i < len; i++) {
882 else if ((c < '0' && c != '-' && c != '.') ||
883 (c < 'A' && c > '9') ||
884 (c > 'Z' && c < 'a' && c != '_') ||
887 int idx = ((int) c) >> 4;
888 result.Append ((char) hexBytes [idx]);
889 idx = ((int) c) & 0x0F;
890 result.Append ((char) hexBytes [idx]);
896 return result.ToString ();
899 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
904 int len = bytes.Length;
908 for (int i = 0; i < len; i++) {
909 char c = (char) bytes [i];
911 stream.WriteByte ((byte) '+');
912 else if ((c < '0' && c != '-' && c != '.') ||
913 (c < 'A' && c > '9') ||
914 (c > 'Z' && c < 'a' && c != '_') ||
916 stream.WriteByte ((byte) '%');
917 int idx = ((int) c) >> 4;
918 stream.WriteByte (hexBytes [idx]);
919 idx = ((int) c) & 0x0F;
920 stream.WriteByte (hexBytes [idx]);
922 stream.WriteByte ((byte) c);
927 public void CancelAsync ()
930 if (async_thread == null)
934 // We first flag things as done, in case the Interrupt hangs
935 // or the thread decides to hang in some other way inside the
936 // event handlers, or if we are stuck somewhere else. This
937 // ensures that the WebClient object is reusable immediately
939 Thread t = async_thread;
945 void CompleteAsync ()
955 public void DownloadDataAsync (Uri address)
957 DownloadDataAsync (address, null);
960 public void DownloadDataAsync (Uri address, object userToken)
963 throw new ArgumentNullException ("address");
969 async_thread = new Thread (delegate (object state) {
970 object [] args = (object []) state;
972 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
973 OnDownloadDataCompleted (
974 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
975 } catch (ThreadInterruptedException){
976 OnDownloadDataCompleted (
977 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
979 } catch (Exception e){
980 OnDownloadDataCompleted (
981 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
984 object [] cb_args = new object [] {address, userToken};
985 async_thread.Start (cb_args);
991 public void DownloadFileAsync (Uri address, string fileName)
993 DownloadFileAsync (address, fileName, null);
996 public void DownloadFileAsync (Uri address, string fileName, object userToken)
999 throw new ArgumentNullException ("address");
1000 if (fileName == null)
1001 throw new ArgumentNullException ("fileName");
1007 async_thread = new Thread (delegate (object state) {
1008 object [] args = (object []) state;
1010 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1011 OnDownloadFileCompleted (
1012 new AsyncCompletedEventArgs (null, false, args [2]));
1013 } catch (ThreadInterruptedException){
1014 OnDownloadFileCompleted (
1015 new AsyncCompletedEventArgs (null, true, args [2]));
1016 } catch (Exception e){
1017 OnDownloadFileCompleted (
1018 new AsyncCompletedEventArgs (e, false, args [2]));
1020 object [] cb_args = new object [] {address, fileName, userToken};
1021 async_thread.Start (cb_args);
1025 // DownloadStringAsync
1027 public void DownloadStringAsync (Uri address)
1029 DownloadStringAsync (address, null);
1032 public void DownloadStringAsync (Uri address, object userToken)
1034 if (address == null)
1035 throw new ArgumentNullException ("address");
1041 async_thread = new Thread (delegate (object state) {
1042 object [] args = (object []) state;
1044 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1045 OnDownloadStringCompleted (
1046 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1047 } catch (ThreadInterruptedException){
1048 OnDownloadStringCompleted (
1049 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1050 } catch (Exception e){
1051 OnDownloadStringCompleted (
1052 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1054 object [] cb_args = new object [] {address, userToken};
1055 async_thread.Start (cb_args);
1061 public void OpenReadAsync (Uri address)
1063 OpenReadAsync (address, null);
1066 public void OpenReadAsync (Uri address, object userToken)
1068 if (address == null)
1069 throw new ArgumentNullException ("address");
1075 async_thread = new Thread (delegate (object state) {
1076 object [] args = (object []) state;
1077 WebRequest request = null;
1079 request = SetupRequest ((Uri) args [0]);
1080 WebResponse response = GetWebResponse (request);
1081 Stream stream = response.GetResponseStream ();
1082 OnOpenReadCompleted (
1083 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1084 } catch (ThreadInterruptedException){
1085 if (request != null)
1088 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1089 } catch (Exception e){
1090 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1092 object [] cb_args = new object [] {address, userToken};
1093 async_thread.Start (cb_args);
1099 public void OpenWriteAsync (Uri address)
1101 OpenWriteAsync (address, null);
1104 public void OpenWriteAsync (Uri address, string method)
1106 OpenWriteAsync (address, method, null);
1109 public void OpenWriteAsync (Uri address, string method, object userToken)
1111 if (address == null)
1112 throw new ArgumentNullException ("address");
1118 async_thread = new Thread (delegate (object state) {
1119 object [] args = (object []) state;
1120 WebRequest request = null;
1122 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1123 Stream stream = request.GetRequestStream ();
1124 OnOpenWriteCompleted (
1125 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1126 } catch (ThreadInterruptedException){
1127 if (request != null)
1129 OnOpenWriteCompleted (
1130 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1131 } catch (Exception e){
1132 OnOpenWriteCompleted (
1133 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1135 object [] cb_args = new object [] {address, method, userToken};
1136 async_thread.Start (cb_args);
1142 public void UploadDataAsync (Uri address, byte [] data)
1144 UploadDataAsync (address, null, data);
1147 public void UploadDataAsync (Uri address, string method, byte [] data)
1149 UploadDataAsync (address, method, data, null);
1152 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1154 if (address == null)
1155 throw new ArgumentNullException ("address");
1157 throw new ArgumentNullException ("data");
1163 async_thread = new Thread (delegate (object state) {
1164 object [] args = (object []) state;
1168 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1170 OnUploadDataCompleted (
1171 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1172 } catch (ThreadInterruptedException){
1173 OnUploadDataCompleted (
1174 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1175 } catch (Exception e){
1176 OnUploadDataCompleted (
1177 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1179 object [] cb_args = new object [] {address, method, data, userToken};
1180 async_thread.Start (cb_args);
1186 public void UploadFileAsync (Uri address, string fileName)
1188 UploadFileAsync (address, null, fileName);
1191 public void UploadFileAsync (Uri address, string method, string fileName)
1193 UploadFileAsync (address, method, fileName, null);
1196 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1198 if (address == null)
1199 throw new ArgumentNullException ("address");
1200 if (fileName == null)
1201 throw new ArgumentNullException ("fileName");
1207 async_thread = new Thread (delegate (object state) {
1208 object [] args = (object []) state;
1212 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1213 OnUploadFileCompleted (
1214 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1215 } catch (ThreadInterruptedException){
1216 OnUploadFileCompleted (
1217 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1218 } catch (Exception e){
1219 OnUploadFileCompleted (
1220 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1222 object [] cb_args = new object [] {address, method, fileName, userToken};
1223 async_thread.Start (cb_args);
1227 // UploadStringAsync
1229 public void UploadStringAsync (Uri address, string data)
1231 UploadStringAsync (address, null, data);
1234 public void UploadStringAsync (Uri address, string method, string data)
1236 UploadStringAsync (address, method, data, null);
1239 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1241 if (address == null)
1242 throw new ArgumentNullException ("address");
1244 throw new ArgumentNullException ("data");
1250 async_thread = new Thread (delegate (object state) {
1251 object [] args = (object []) state;
1254 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1255 OnUploadStringCompleted (
1256 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1257 } catch (ThreadInterruptedException){
1258 OnUploadStringCompleted (
1259 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1260 } catch (Exception e){
1261 OnUploadStringCompleted (
1262 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1264 object [] cb_args = new object [] {address, method, data, userToken};
1265 async_thread.Start (cb_args);
1269 // UploadValuesAsync
1271 public void UploadValuesAsync (Uri address, NameValueCollection values)
1273 UploadValuesAsync (address, null, values);
1276 public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
1278 UploadValuesAsync (address, method, values, null);
1281 public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
1283 if (address == null)
1284 throw new ArgumentNullException ("address");
1286 throw new ArgumentNullException ("values");
1292 async_thread = new Thread (delegate (object state) {
1293 object [] args = (object []) state;
1295 byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1296 OnUploadValuesCompleted (
1297 new UploadValuesCompletedEventArgs (data, null, false, args [3]));
1298 } catch (ThreadInterruptedException){
1299 OnUploadValuesCompleted (
1300 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1301 } catch (Exception e){
1302 OnUploadValuesCompleted (
1303 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1305 object [] cb_args = new object [] {address, method, values, userToken};
1306 async_thread.Start (cb_args);
1310 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
1313 if (DownloadDataCompleted != null)
1314 DownloadDataCompleted (this, args);
1317 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
1320 if (DownloadFileCompleted != null)
1321 DownloadFileCompleted (this, args);
1324 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1326 if (DownloadProgressChanged != null)
1327 DownloadProgressChanged (this, e);
1330 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
1333 if (DownloadStringCompleted != null)
1334 DownloadStringCompleted (this, args);
1337 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
1340 if (OpenReadCompleted != null)
1341 OpenReadCompleted (this, args);
1344 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
1347 if (OpenWriteCompleted != null)
1348 OpenWriteCompleted (this, args);
1351 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
1354 if (UploadDataCompleted != null)
1355 UploadDataCompleted (this, args);
1358 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
1361 if (UploadFileCompleted != null)
1362 UploadFileCompleted (this, args);
1365 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1367 if (UploadProgressChanged != null)
1368 UploadProgressChanged (this, e);
1371 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
1374 if (UploadStringCompleted != null)
1375 UploadStringCompleted (this, args);
1378 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
1381 if (UploadValuesCompleted != null)
1382 UploadValuesCompleted (this, args);
1385 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1387 WebResponse response = request.EndGetResponse (result);
1388 responseHeaders = response.Headers;
1392 protected virtual WebRequest GetWebRequest (Uri address)
1394 return WebRequest.Create (address);
1397 protected virtual WebResponse GetWebResponse (WebRequest request)
1399 WebResponse response = request.GetResponse ();
1400 responseHeaders = response.Headers;