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 (Exception ex) {
283 throw new WebException ("An error occurred " +
284 "performing a WebClient request.", ex);
290 public void DownloadFile (string address, string fileName)
294 throw new ArgumentNullException ("address");
297 DownloadFile (CreateUri (address), fileName);
303 void DownloadFile (Uri address, string fileName)
307 throw new ArgumentNullException ("address");
308 if (fileName == null)
309 throw new ArgumentNullException ("fileName");
317 DownloadFileCore (address, fileName, null);
318 } catch (Exception ex) {
319 throw new WebException ("An error occurred " +
320 "performing a WebClient request.", ex);
326 void DownloadFileCore (Uri address, string fileName, object userToken)
328 WebRequest request = null;
330 using (FileStream f = new FileStream (fileName, FileMode.Create)) {
332 request = SetupRequest (address);
333 WebResponse response = GetWebResponse (request);
334 Stream st = response.GetResponseStream ();
336 int cLength = (int) response.ContentLength;
337 int length = (cLength <= -1 || cLength > 32*1024) ? 32*1024 : cLength;
338 byte [] buffer = new byte [length];
342 long notify_total = 0;
344 while ((nread = st.Read (buffer, 0, length)) != 0){
347 notify_total += nread;
348 OnDownloadProgressChanged (
349 new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
353 f.Write (buffer, 0, nread);
355 } catch (ThreadInterruptedException){
365 public Stream OpenRead (string address)
369 throw new ArgumentNullException ("address");
372 return OpenRead (CreateUri (address));
378 Stream OpenRead (Uri address)
382 throw new ArgumentNullException ("address");
385 WebRequest request = null;
391 request = SetupRequest (address);
392 WebResponse response = GetWebResponse (request);
393 return response.GetResponseStream ();
394 } catch (Exception ex) {
395 throw new WebException ("An error occurred " +
396 "performing a WebClient request.", ex);
404 public Stream OpenWrite (string address)
408 throw new ArgumentNullException ("address");
411 return OpenWrite (CreateUri (address));
414 public Stream OpenWrite (string address, string method)
418 throw new ArgumentNullException ("address");
421 return OpenWrite (CreateUri (address), method);
427 Stream OpenWrite (Uri address)
429 return OpenWrite (address, (string) null);
435 Stream OpenWrite (Uri address, string method)
439 throw new ArgumentNullException ("address");
447 WebRequest request = SetupRequest (address, method, true);
448 return request.GetRequestStream ();
449 } catch (Exception ex) {
450 throw new WebException ("An error occurred " +
451 "performing a WebClient request.", ex);
457 private string DetermineMethod (Uri address, string method, bool is_upload)
463 if (address.Scheme == Uri.UriSchemeFtp)
464 return (is_upload) ? "STOR" : "RETR";
466 return (is_upload) ? "POST" : "GET";
471 public byte [] UploadData (string address, byte [] data)
475 throw new ArgumentNullException ("address");
478 return UploadData (CreateUri (address), data);
481 public byte [] UploadData (string address, string method, byte [] data)
485 throw new ArgumentNullException ("address");
488 return UploadData (CreateUri (address), method, data);
494 byte [] UploadData (Uri address, byte [] data)
496 return UploadData (address, (string) null, data);
502 byte [] UploadData (Uri address, string method, byte [] data)
506 throw new ArgumentNullException ("address");
508 throw new ArgumentNullException ("data");
516 return UploadDataCore (address, method, data, null);
517 } catch (WebException) {
519 } catch (Exception ex) {
520 throw new WebException ("An error occurred " +
521 "performing a WebClient request.", ex);
527 byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
531 throw new ArgumentNullException ("address");
533 throw new ArgumentNullException ("data");
536 WebRequest request = SetupRequest (address, method, true);
538 int contentLength = data.Length;
539 request.ContentLength = contentLength;
540 using (Stream stream = request.GetRequestStream ()) {
541 stream.Write (data, 0, contentLength);
544 WebResponse response = GetWebResponse (request);
545 Stream st = response.GetResponseStream ();
546 return ReadAll (st, (int) response.ContentLength, userToken);
547 } catch (ThreadInterruptedException){
556 public byte [] UploadFile (string address, string fileName)
560 throw new ArgumentNullException ("address");
563 return UploadFile (CreateUri (address), fileName);
569 byte [] UploadFile (Uri address, string fileName)
571 return UploadFile (address, (string) null, fileName);
574 public byte [] UploadFile (string address, string method, string fileName)
576 return UploadFile (CreateUri (address), method, fileName);
582 byte [] UploadFile (Uri address, string method, string fileName)
586 throw new ArgumentNullException ("address");
587 if (fileName == null)
588 throw new ArgumentNullException ("fileName");
596 return UploadFileCore (address, method, fileName, null);
597 } catch (Exception ex) {
598 throw new WebException ("An error occurred " +
599 "performing a WebClient request.", ex);
605 byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
609 throw new ArgumentNullException ("address");
612 string fileCType = Headers ["Content-Type"];
613 if (fileCType != null) {
614 string lower = fileCType.ToLower ();
615 if (lower.StartsWith ("multipart/"))
616 throw new WebException ("Content-Type cannot be set to a multipart" +
617 " type for this request.");
619 fileCType = "application/octet-stream";
622 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
623 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
624 Stream reqStream = null;
625 Stream fStream = null;
626 byte [] resultBytes = null;
628 fileName = Path.GetFullPath (fileName);
630 WebRequest request = null;
632 fStream = File.OpenRead (fileName);
633 request = SetupRequest (address, method, true);
634 reqStream = request.GetRequestStream ();
635 byte [] realBoundary = Encoding.ASCII.GetBytes ("--" + boundary + "\r\n");
636 reqStream.Write (realBoundary, 0, realBoundary.Length);
637 string partHeaders = String.Format ("Content-Disposition: form-data; " +
638 "name=\"file\"; filename=\"{0}\"\r\n" +
639 "Content-Type: {1}\r\n\r\n",
640 Path.GetFileName (fileName), fileCType);
642 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
643 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
645 byte [] buffer = new byte [4096];
646 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
647 reqStream.Write (buffer, 0, nread);
649 reqStream.WriteByte ((byte) '\r');
650 reqStream.WriteByte ((byte) '\n');
651 reqStream.Write (realBoundary, 0, realBoundary.Length);
654 WebResponse response = GetWebResponse (request);
655 Stream st = response.GetResponseStream ();
656 resultBytes = ReadAll (st, (int) response.ContentLength, userToken);
657 } catch (ThreadInterruptedException){
665 if (reqStream != null)
672 public byte[] UploadValues (string address, NameValueCollection data)
676 throw new ArgumentNullException ("address");
679 return UploadValues (CreateUri (address), data);
682 public byte[] UploadValues (string address, string method, NameValueCollection data)
686 throw new ArgumentNullException ("address");
689 return UploadValues (CreateUri (address), method, data);
695 byte[] UploadValues (Uri address, NameValueCollection data)
697 return UploadValues (address, (string) null, data);
703 byte[] UploadValues (Uri address, string method, NameValueCollection data)
707 throw new ArgumentNullException ("address");
709 throw new ArgumentNullException ("data");
717 return UploadValuesCore (address, method, data, null);
718 } catch (Exception ex) {
719 throw new WebException ("An error occurred " +
720 "performing a WebClient request.", ex);
726 byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
730 throw new ArgumentNullException ("data");
733 string cType = Headers ["Content-Type"];
734 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
735 throw new WebException ("Content-Type header cannot be changed from its default " +
736 "value for this request.");
738 Headers ["Content-Type"] = urlEncodedCType;
739 WebRequest request = SetupRequest (uri, method, true);
741 MemoryStream tmpStream = new MemoryStream ();
742 foreach (string key in data) {
743 byte [] bytes = Encoding.UTF8.GetBytes (key);
744 UrlEncodeAndWrite (tmpStream, bytes);
745 tmpStream.WriteByte ((byte) '=');
746 bytes = Encoding.UTF8.GetBytes (data [key]);
747 UrlEncodeAndWrite (tmpStream, bytes);
748 tmpStream.WriteByte ((byte) '&');
751 int length = (int) tmpStream.Length;
753 tmpStream.SetLength (--length); // remove trailing '&'
755 byte [] buf = tmpStream.GetBuffer ();
756 request.ContentLength = length;
757 using (Stream rqStream = request.GetRequestStream ()) {
758 rqStream.Write (buf, 0, length);
762 WebResponse response = GetWebResponse (request);
763 Stream st = response.GetResponseStream ();
764 return ReadAll (st, (int) response.ContentLength, userToken);
765 } catch (ThreadInterruptedException) {
772 public string DownloadString (string address)
775 throw new ArgumentNullException ("address");
777 return encoding.GetString (DownloadData (CreateUri (address)));
780 public string DownloadString (Uri address)
783 throw new ArgumentNullException ("address");
785 return encoding.GetString (DownloadData (CreateUri (address)));
788 public string UploadString (string address, string data)
791 throw new ArgumentNullException ("address");
793 throw new ArgumentNullException ("data");
795 byte [] resp = UploadData (address, encoding.GetBytes (data));
796 return encoding.GetString (resp);
799 public string UploadString (string address, string method, string data)
802 throw new ArgumentNullException ("address");
804 throw new ArgumentNullException ("data");
806 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
807 return encoding.GetString (resp);
810 public string UploadString (Uri address, string data)
813 throw new ArgumentNullException ("address");
815 throw new ArgumentNullException ("data");
817 byte [] resp = UploadData (address, encoding.GetBytes (data));
818 return encoding.GetString (resp);
821 public string UploadString (Uri address, string method, string data)
824 throw new ArgumentNullException ("address");
826 throw new ArgumentNullException ("data");
828 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
829 return encoding.GetString (resp);
832 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
833 public event AsyncCompletedEventHandler DownloadFileCompleted;
834 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
835 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
836 public event OpenReadCompletedEventHandler OpenReadCompleted;
837 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
838 public event UploadDataCompletedEventHandler UploadDataCompleted;
839 public event UploadFileCompletedEventHandler UploadFileCompleted;
840 public event UploadProgressChangedEventHandler UploadProgressChanged;
841 public event UploadStringCompletedEventHandler UploadStringCompleted;
842 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
845 Uri CreateUri (string address)
849 return MakeUri (address);
850 } catch (Exception ex) {
851 throw new WebException ("An error occurred " +
852 "performing a WebClient request.", ex);
855 return MakeUri (address);
860 Uri CreateUri (Uri address)
862 string query = address.Query;
863 if (String.IsNullOrEmpty (query))
864 query = GetQueryString (true);
866 if (baseAddress == null && query == null)
869 if (baseAddress == null)
870 return new Uri (address.ToString () + query, (query != null));
873 return new Uri (baseAddress, address.ToString ());
875 return new Uri (baseAddress, address.ToString () + query, (query != null));
880 string GetQueryString (bool add_qmark)
882 if (queryString == null || queryString.Count == 0)
885 StringBuilder sb = new StringBuilder ();
889 foreach (string key in queryString)
890 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
893 sb.Length--; // removes last '&' or the '?' if empty.
898 return sb.ToString ();
901 Uri MakeUri (string path)
903 string query = GetQueryString (true);
904 if (baseAddress == null && query == null) {
906 return new Uri (path);
908 } catch (ArgumentNullException) {
909 path = Path.GetFullPath (path);
910 return new Uri ("file://" + path);
912 } catch (UriFormatException) {
913 path = Path.GetFullPath (path);
914 return new Uri ("file://" + path);
918 if (baseAddress == null)
919 return new Uri (path + query, (query != null));
922 return new Uri (baseAddress, path);
924 return new Uri (baseAddress, path + query, (query != null));
927 WebRequest SetupRequest (Uri uri)
929 WebRequest request = WebRequest.Create (uri);
932 request.Proxy = Proxy;
934 request.Credentials = credentials;
936 // Special headers. These are properties of HttpWebRequest.
937 // What do we do with other requests differnt from HttpWebRequest?
938 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
939 HttpWebRequest req = (HttpWebRequest) request;
940 string expect = headers ["Expect"];
941 string contentType = headers ["Content-Type"];
942 string accept = headers ["Accept"];
943 string connection = headers ["Connection"];
944 string userAgent = headers ["User-Agent"];
945 string referer = headers ["Referer"];
946 headers.RemoveInternal ("Expect");
947 headers.RemoveInternal ("Content-Type");
948 headers.RemoveInternal ("Accept");
949 headers.RemoveInternal ("Connection");
950 headers.RemoveInternal ("Referer");
951 headers.RemoveInternal ("User-Agent");
952 request.Headers = headers;
954 if (expect != null && expect.Length > 0)
957 if (accept != null && accept.Length > 0)
960 if (contentType != null && contentType.Length > 0)
961 req.ContentType = contentType;
963 if (connection != null && connection.Length > 0)
964 req.Connection = connection;
966 if (userAgent != null && userAgent.Length > 0)
967 req.UserAgent = userAgent;
969 if (referer != null && referer.Length > 0)
970 req.Referer = referer;
973 responseHeaders = null;
977 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
979 WebRequest request = SetupRequest (uri);
980 request.Method = DetermineMethod (uri, method, is_upload);
984 byte [] ReadAll (Stream stream, int length, object userToken)
986 MemoryStream ms = null;
988 bool nolength = (length == -1);
989 int size = ((nolength) ? 8192 : length);
991 ms = new MemoryStream ();
996 byte [] buffer = new byte [size];
997 while ((nread = stream.Read (buffer, offset, size)) != 0) {
999 ms.Write (buffer, 0, nread);
1007 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
1013 return ms.ToArray ();
1018 string UrlEncode (string str)
1020 StringBuilder result = new StringBuilder ();
1022 int len = str.Length;
1023 for (int i = 0; i < len; i++) {
1026 result.Append ('+');
1027 else if ((c < '0' && c != '-' && c != '.') ||
1028 (c < 'A' && c > '9') ||
1029 (c > 'Z' && c < 'a' && c != '_') ||
1031 result.Append ('%');
1032 int idx = ((int) c) >> 4;
1033 result.Append ((char) hexBytes [idx]);
1034 idx = ((int) c) & 0x0F;
1035 result.Append ((char) hexBytes [idx]);
1041 return result.ToString ();
1044 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
1049 int len = bytes.Length;
1053 for (int i = 0; i < len; i++) {
1054 char c = (char) bytes [i];
1056 stream.WriteByte ((byte) '+');
1057 else if ((c < '0' && c != '-' && c != '.') ||
1058 (c < 'A' && c > '9') ||
1059 (c > 'Z' && c < 'a' && c != '_') ||
1061 stream.WriteByte ((byte) '%');
1062 int idx = ((int) c) >> 4;
1063 stream.WriteByte (hexBytes [idx]);
1064 idx = ((int) c) & 0x0F;
1065 stream.WriteByte (hexBytes [idx]);
1067 stream.WriteByte ((byte) c);
1073 public void CancelAsync ()
1076 if (async_thread == null)
1080 // We first flag things as done, in case the Interrupt hangs
1081 // or the thread decides to hang in some other way inside the
1082 // event handlers, or if we are stuck somewhere else. This
1083 // ensures that the WebClient object is reusable immediately
1085 Thread t = async_thread;
1091 void CompleteAsync ()
1095 async_thread = null;
1099 // DownloadDataAsync
1101 public void DownloadDataAsync (Uri address)
1103 DownloadDataAsync (address, null);
1106 public void DownloadDataAsync (Uri address, object userToken)
1108 if (address == null)
1109 throw new ArgumentNullException ("address");
1115 async_thread = new Thread (delegate (object state) {
1116 object [] args = (object []) state;
1118 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
1119 OnDownloadDataCompleted (
1120 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
1121 } catch (ThreadInterruptedException){
1122 OnDownloadDataCompleted (
1123 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
1125 } catch (Exception e){
1126 OnDownloadDataCompleted (
1127 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
1130 object [] cb_args = new object [] {address, userToken};
1131 async_thread.Start (cb_args);
1135 // DownloadFileAsync
1137 public void DownloadFileAsync (Uri address, string fileName)
1139 DownloadFileAsync (address, fileName, null);
1142 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1144 if (address == null)
1145 throw new ArgumentNullException ("address");
1146 if (fileName == null)
1147 throw new ArgumentNullException ("fileName");
1153 async_thread = new Thread (delegate (object state) {
1154 object [] args = (object []) state;
1156 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1157 OnDownloadFileCompleted (
1158 new AsyncCompletedEventArgs (null, false, args [2]));
1159 } catch (ThreadInterruptedException){
1160 OnDownloadFileCompleted (
1161 new AsyncCompletedEventArgs (null, true, args [2]));
1162 } catch (Exception e){
1163 OnDownloadFileCompleted (
1164 new AsyncCompletedEventArgs (e, false, args [2]));
1166 object [] cb_args = new object [] {address, fileName, userToken};
1167 async_thread.Start (cb_args);
1171 // DownloadStringAsync
1173 public void DownloadStringAsync (Uri address)
1175 DownloadStringAsync (address, null);
1178 public void DownloadStringAsync (Uri address, object userToken)
1180 if (address == null)
1181 throw new ArgumentNullException ("address");
1187 async_thread = new Thread (delegate (object state) {
1188 object [] args = (object []) state;
1190 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1191 OnDownloadStringCompleted (
1192 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1193 } catch (ThreadInterruptedException){
1194 OnDownloadStringCompleted (
1195 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1196 } catch (Exception e){
1197 OnDownloadStringCompleted (
1198 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1200 object [] cb_args = new object [] {address, userToken};
1201 async_thread.Start (cb_args);
1207 public void OpenReadAsync (Uri address)
1209 OpenReadAsync (address, null);
1212 public void OpenReadAsync (Uri address, object userToken)
1214 if (address == null)
1215 throw new ArgumentNullException ("address");
1221 async_thread = new Thread (delegate (object state) {
1222 object [] args = (object []) state;
1223 WebRequest request = null;
1225 request = SetupRequest ((Uri) args [0]);
1226 WebResponse response = GetWebResponse (request);
1227 Stream stream = response.GetResponseStream ();
1228 OnOpenReadCompleted (
1229 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1230 } catch (ThreadInterruptedException){
1231 if (request != null)
1234 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1235 } catch (Exception e){
1236 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1238 object [] cb_args = new object [] {address, userToken};
1239 async_thread.Start (cb_args);
1245 public void OpenWriteAsync (Uri address)
1247 OpenWriteAsync (address, null);
1250 public void OpenWriteAsync (Uri address, string method)
1252 OpenWriteAsync (address, method, null);
1255 public void OpenWriteAsync (Uri address, string method, object userToken)
1257 if (address == null)
1258 throw new ArgumentNullException ("address");
1264 async_thread = new Thread (delegate (object state) {
1265 object [] args = (object []) state;
1266 WebRequest request = null;
1268 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1269 Stream stream = request.GetRequestStream ();
1270 OnOpenWriteCompleted (
1271 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1272 } catch (ThreadInterruptedException){
1273 if (request != null)
1275 OnOpenWriteCompleted (
1276 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1277 } catch (Exception e){
1278 OnOpenWriteCompleted (
1279 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1281 object [] cb_args = new object [] {address, method, userToken};
1282 async_thread.Start (cb_args);
1288 public void UploadDataAsync (Uri address, byte [] data)
1290 UploadDataAsync (address, null, data);
1293 public void UploadDataAsync (Uri address, string method, byte [] data)
1295 UploadDataAsync (address, method, data, null);
1298 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1300 if (address == null)
1301 throw new ArgumentNullException ("address");
1303 throw new ArgumentNullException ("data");
1309 async_thread = new Thread (delegate (object state) {
1310 object [] args = (object []) state;
1314 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1316 OnUploadDataCompleted (
1317 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1318 } catch (ThreadInterruptedException){
1319 OnUploadDataCompleted (
1320 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1321 } catch (Exception e){
1322 OnUploadDataCompleted (
1323 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1325 object [] cb_args = new object [] {address, method, data, userToken};
1326 async_thread.Start (cb_args);
1332 public void UploadFileAsync (Uri address, string fileName)
1334 UploadFileAsync (address, null, fileName);
1337 public void UploadFileAsync (Uri address, string method, string fileName)
1339 UploadFileAsync (address, method, fileName, null);
1342 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1344 if (address == null)
1345 throw new ArgumentNullException ("address");
1346 if (fileName == null)
1347 throw new ArgumentNullException ("fileName");
1353 async_thread = new Thread (delegate (object state) {
1354 object [] args = (object []) state;
1358 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1359 OnUploadFileCompleted (
1360 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1361 } catch (ThreadInterruptedException){
1362 OnUploadFileCompleted (
1363 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1364 } catch (Exception e){
1365 OnUploadFileCompleted (
1366 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1368 object [] cb_args = new object [] {address, method, fileName, userToken};
1369 async_thread.Start (cb_args);
1373 // UploadStringAsync
1375 public void UploadStringAsync (Uri address, string data)
1377 UploadStringAsync (address, null, data);
1380 public void UploadStringAsync (Uri address, string method, string data)
1382 UploadStringAsync (address, method, data, null);
1385 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1387 if (address == null)
1388 throw new ArgumentNullException ("address");
1390 throw new ArgumentNullException ("data");
1396 async_thread = new Thread (delegate (object state) {
1397 object [] args = (object []) state;
1400 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1401 OnUploadStringCompleted (
1402 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1403 } catch (ThreadInterruptedException){
1404 OnUploadStringCompleted (
1405 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1406 } catch (Exception e){
1407 OnUploadStringCompleted (
1408 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1410 object [] cb_args = new object [] {address, method, data, userToken};
1411 async_thread.Start (cb_args);
1415 // UploadValuesAsync
1417 public void UploadValuesAsync (Uri address, NameValueCollection values)
1419 UploadValuesAsync (address, null, values);
1422 public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
1424 UploadValuesAsync (address, method, values, null);
1427 public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
1429 if (address == null)
1430 throw new ArgumentNullException ("address");
1432 throw new ArgumentNullException ("values");
1438 async_thread = new Thread (delegate (object state) {
1439 object [] args = (object []) state;
1441 byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1442 OnUploadValuesCompleted (
1443 new UploadValuesCompletedEventArgs (data, null, false, args [3]));
1444 } catch (ThreadInterruptedException){
1445 OnUploadValuesCompleted (
1446 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1447 } catch (Exception e){
1448 OnUploadValuesCompleted (
1449 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1451 object [] cb_args = new object [] {address, method, values, userToken};
1452 async_thread.Start (cb_args);
1456 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
1459 if (DownloadDataCompleted != null)
1460 DownloadDataCompleted (this, args);
1463 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
1466 if (DownloadFileCompleted != null)
1467 DownloadFileCompleted (this, args);
1470 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1472 if (DownloadProgressChanged != null)
1473 DownloadProgressChanged (this, e);
1476 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
1479 if (DownloadStringCompleted != null)
1480 DownloadStringCompleted (this, args);
1483 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
1486 if (OpenReadCompleted != null)
1487 OpenReadCompleted (this, args);
1490 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
1493 if (OpenWriteCompleted != null)
1494 OpenWriteCompleted (this, args);
1497 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
1500 if (UploadDataCompleted != null)
1501 UploadDataCompleted (this, args);
1504 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
1507 if (UploadFileCompleted != null)
1508 UploadFileCompleted (this, args);
1511 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1513 if (UploadProgressChanged != null)
1514 UploadProgressChanged (this, e);
1517 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
1520 if (UploadStringCompleted != null)
1521 UploadStringCompleted (this, args);
1524 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
1527 if (UploadValuesCompleted != null)
1528 UploadValuesCompleted (this, args);
1531 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1533 WebResponse response = request.EndGetResponse (result);
1534 responseHeaders = response.Headers;
1542 WebRequest GetWebRequest (Uri address)
1544 return SetupRequest (address);
1550 WebResponse GetWebResponse (WebRequest request)
1552 WebResponse response = request.GetResponse ();
1553 responseHeaders = response.Headers;