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 == "") {
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 ("value");
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 = request.GetResponse ();
276 Stream st = ProcessResponse (response);
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 = request.GetResponse ();
334 Stream st = ProcessResponse (response);
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 = request.GetResponse ();
393 return ProcessResponse (response);
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 = request.GetResponse ();
545 Stream st = ProcessResponse (response);
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 = request.GetResponse ();
655 Stream st = ProcessResponse (response);
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 Stream rqStream = request.GetRequestStream ();
742 MemoryStream tmpStream = new MemoryStream ();
743 foreach (string key in data) {
744 byte [] bytes = Encoding.UTF8.GetBytes (key);
745 UrlEncodeAndWrite (tmpStream, bytes);
746 tmpStream.WriteByte ((byte) '=');
747 bytes = Encoding.UTF8.GetBytes (data [key]);
748 UrlEncodeAndWrite (tmpStream, bytes);
749 tmpStream.WriteByte ((byte) '&');
752 int length = (int) tmpStream.Length;
754 tmpStream.SetLength (--length); // remove trailing '&'
756 byte [] buf = tmpStream.GetBuffer ();
757 rqStream.Write (buf, 0, length);
761 WebResponse response = request.GetResponse ();
762 Stream st = ProcessResponse (response);
763 return ReadAll (st, (int) response.ContentLength, userToken);
764 } catch (ThreadInterruptedException) {
771 public string DownloadString (string address)
774 throw new ArgumentNullException ("address");
776 return encoding.GetString (DownloadData (CreateUri (address)));
779 public string DownloadString (Uri address)
782 throw new ArgumentNullException ("address");
784 return encoding.GetString (DownloadData (CreateUri (address)));
787 public string UploadString (string address, string data)
790 throw new ArgumentNullException ("address");
792 throw new ArgumentNullException ("data");
794 byte [] resp = UploadData (address, encoding.GetBytes (data));
795 return encoding.GetString (resp);
798 public string UploadString (string address, string method, string data)
801 throw new ArgumentNullException ("address");
803 throw new ArgumentNullException ("data");
805 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
806 return encoding.GetString (resp);
809 public string UploadString (Uri address, string data)
812 throw new ArgumentNullException ("address");
814 throw new ArgumentNullException ("data");
816 byte [] resp = UploadData (address, encoding.GetBytes (data));
817 return encoding.GetString (resp);
820 public string UploadString (Uri address, string method, string data)
823 throw new ArgumentNullException ("address");
825 throw new ArgumentNullException ("data");
827 byte [] resp = UploadData (address, method, encoding.GetBytes (data));
828 return encoding.GetString (resp);
831 public event DownloadDataCompletedEventHandler DownloadDataCompleted;
832 public event AsyncCompletedEventHandler DownloadFileCompleted;
833 public event DownloadProgressChangedEventHandler DownloadProgressChanged;
834 public event DownloadStringCompletedEventHandler DownloadStringCompleted;
835 public event OpenReadCompletedEventHandler OpenReadCompleted;
836 public event OpenWriteCompletedEventHandler OpenWriteCompleted;
837 public event UploadDataCompletedEventHandler UploadDataCompleted;
838 public event UploadFileCompletedEventHandler UploadFileCompleted;
839 public event UploadProgressChangedEventHandler UploadProgressChanged;
840 public event UploadStringCompletedEventHandler UploadStringCompleted;
841 public event UploadValuesCompletedEventHandler UploadValuesCompleted;
844 Uri CreateUri (string address)
848 return MakeUri (address);
849 } catch (Exception ex) {
850 throw new WebException ("An error occurred " +
851 "performing a WebClient request.", ex);
854 return MakeUri (address);
859 Uri CreateUri (Uri address)
861 string query = address.Query;
862 if (String.IsNullOrEmpty (query))
863 query = GetQueryString (true);
865 if (baseAddress == null && query == null)
868 if (baseAddress == null)
869 return new Uri (address.ToString () + query, (query != null));
872 return new Uri (baseAddress, address.ToString ());
874 return new Uri (baseAddress, address.ToString () + query, (query != null));
879 string GetQueryString (bool add_qmark)
881 if (queryString == null || queryString.Count == 0)
884 StringBuilder sb = new StringBuilder ();
888 foreach (string key in queryString)
889 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
892 sb.Length--; // removes last '&' or the '?' if empty.
897 return sb.ToString ();
900 Uri MakeUri (string path)
902 string query = GetQueryString (true);
903 if (baseAddress == null && query == null) {
905 return new Uri (path);
907 } catch (ArgumentNullException) {
908 path = Path.GetFullPath (path);
909 return new Uri ("file://" + path);
911 } catch (UriFormatException) {
912 path = Path.GetFullPath (path);
913 return new Uri ("file://" + path);
917 if (baseAddress == null)
918 return new Uri (path + query, (query != null));
921 return new Uri (baseAddress, path);
923 return new Uri (baseAddress, path + query, (query != null));
926 WebRequest SetupRequest (Uri uri)
928 WebRequest request = WebRequest.Create (uri);
931 request.Proxy = Proxy;
933 request.Credentials = credentials;
935 // Special headers. These are properties of HttpWebRequest.
936 // What do we do with other requests differnt from HttpWebRequest?
937 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
938 HttpWebRequest req = (HttpWebRequest) request;
939 string expect = headers ["Expect"];
940 string contentType = headers ["Content-Type"];
941 string accept = headers ["Accept"];
942 string connection = headers ["Connection"];
943 string userAgent = headers ["User-Agent"];
944 string referer = headers ["Referer"];
945 headers.RemoveInternal ("Expect");
946 headers.RemoveInternal ("Content-Type");
947 headers.RemoveInternal ("Accept");
948 headers.RemoveInternal ("Connection");
949 headers.RemoveInternal ("Referer");
950 headers.RemoveInternal ("User-Agent");
951 request.Headers = headers;
953 if (expect != null && expect.Length > 0)
956 if (accept != null && accept.Length > 0)
959 if (contentType != null && contentType.Length > 0)
960 req.ContentType = contentType;
962 if (connection != null && connection.Length > 0)
963 req.Connection = connection;
965 if (userAgent != null && userAgent.Length > 0)
966 req.UserAgent = userAgent;
968 if (referer != null && referer.Length > 0)
969 req.Referer = referer;
972 responseHeaders = null;
976 WebRequest SetupRequest (Uri uri, string method, bool is_upload)
978 WebRequest request = SetupRequest (uri);
979 request.Method = DetermineMethod (uri, method, is_upload);
983 Stream ProcessResponse (WebResponse response)
985 responseHeaders = response.Headers;
986 return response.GetResponseStream ();
989 byte [] ReadAll (Stream stream, int length, object userToken)
991 MemoryStream ms = null;
993 bool nolength = (length == -1);
994 int size = ((nolength) ? 8192 : length);
996 ms = new MemoryStream ();
1001 byte [] buffer = new byte [size];
1002 while ((nread = stream.Read (buffer, offset, size)) != 0) {
1004 ms.Write (buffer, 0, nread);
1012 OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
1018 return ms.ToArray ();
1023 string UrlEncode (string str)
1025 StringBuilder result = new StringBuilder ();
1027 int len = str.Length;
1028 for (int i = 0; i < len; i++) {
1031 result.Append ('+');
1032 else if ((c < '0' && c != '-' && c != '.') ||
1033 (c < 'A' && c > '9') ||
1034 (c > 'Z' && c < 'a' && c != '_') ||
1036 result.Append ('%');
1037 int idx = ((int) c) >> 4;
1038 result.Append ((char) hexBytes [idx]);
1039 idx = ((int) c) & 0x0F;
1040 result.Append ((char) hexBytes [idx]);
1046 return result.ToString ();
1049 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
1054 int len = bytes.Length;
1058 for (int i = 0; i < len; i++) {
1059 char c = (char) bytes [i];
1061 stream.WriteByte ((byte) '+');
1062 else if ((c < '0' && c != '-' && c != '.') ||
1063 (c < 'A' && c > '9') ||
1064 (c > 'Z' && c < 'a' && c != '_') ||
1066 stream.WriteByte ((byte) '%');
1067 int idx = ((int) c) >> 4;
1068 stream.WriteByte (hexBytes [idx]);
1069 idx = ((int) c) & 0x0F;
1070 stream.WriteByte (hexBytes [idx]);
1072 stream.WriteByte ((byte) c);
1078 public void CancelAsync ()
1081 if (async_thread == null)
1085 // We first flag things as done, in case the Interrupt hangs
1086 // or the thread decides to hang in some other way inside the
1087 // event handlers, or if we are stuck somewhere else. This
1088 // ensures that the WebClient object is reusable immediately
1090 Thread t = async_thread;
1096 void CompleteAsync ()
1100 async_thread = null;
1104 // DownloadDataAsync
1106 public void DownloadDataAsync (Uri address)
1108 DownloadDataAsync (address, null);
1111 public void DownloadDataAsync (Uri address, object userToken)
1113 if (address == null)
1114 throw new ArgumentNullException ("address");
1120 async_thread = new Thread (delegate (object state) {
1121 object [] args = (object []) state;
1123 byte [] data = DownloadDataCore ((Uri) args [0], args [1]);
1124 OnDownloadDataCompleted (
1125 new DownloadDataCompletedEventArgs (data, null, false, args [1]));
1126 } catch (ThreadInterruptedException){
1127 OnDownloadDataCompleted (
1128 new DownloadDataCompletedEventArgs (null, null, true, args [1]));
1130 } catch (Exception e){
1131 OnDownloadDataCompleted (
1132 new DownloadDataCompletedEventArgs (null, e, false, args [1]));
1135 object [] cb_args = new object [] {address, userToken};
1136 async_thread.Start (cb_args);
1140 // DownloadFileAsync
1142 public void DownloadFileAsync (Uri address, string fileName)
1144 DownloadFileAsync (address, fileName, null);
1147 public void DownloadFileAsync (Uri address, string fileName, object userToken)
1149 if (address == null)
1150 throw new ArgumentNullException ("address");
1151 if (fileName == null)
1152 throw new ArgumentNullException ("fileName");
1158 async_thread = new Thread (delegate (object state) {
1159 object [] args = (object []) state;
1161 DownloadFileCore ((Uri) args [0], (string) args [1], args [2]);
1162 OnDownloadFileCompleted (
1163 new AsyncCompletedEventArgs (null, false, args [2]));
1164 } catch (ThreadInterruptedException){
1165 OnDownloadFileCompleted (
1166 new AsyncCompletedEventArgs (null, true, args [2]));
1167 } catch (Exception e){
1168 OnDownloadFileCompleted (
1169 new AsyncCompletedEventArgs (e, false, args [2]));
1171 object [] cb_args = new object [] {address, fileName, userToken};
1172 async_thread.Start (cb_args);
1176 // DownloadStringAsync
1178 public void DownloadStringAsync (Uri address)
1180 DownloadStringAsync (address, null);
1183 public void DownloadStringAsync (Uri address, object userToken)
1185 if (address == null)
1186 throw new ArgumentNullException ("address");
1192 async_thread = new Thread (delegate (object state) {
1193 object [] args = (object []) state;
1195 string data = encoding.GetString (DownloadDataCore ((Uri) args [0], args [1]));
1196 OnDownloadStringCompleted (
1197 new DownloadStringCompletedEventArgs (data, null, false, args [1]));
1198 } catch (ThreadInterruptedException){
1199 OnDownloadStringCompleted (
1200 new DownloadStringCompletedEventArgs (null, null, true, args [1]));
1201 } catch (Exception e){
1202 OnDownloadStringCompleted (
1203 new DownloadStringCompletedEventArgs (null, e, false, args [1]));
1205 object [] cb_args = new object [] {address, userToken};
1206 async_thread.Start (cb_args);
1212 public void OpenReadAsync (Uri address)
1214 OpenReadAsync (address, null);
1217 public void OpenReadAsync (Uri address, object userToken)
1219 if (address == null)
1220 throw new ArgumentNullException ("address");
1226 async_thread = new Thread (delegate (object state) {
1227 object [] args = (object []) state;
1228 WebRequest request = null;
1230 request = SetupRequest ((Uri) args [0]);
1231 WebResponse response = request.GetResponse ();
1232 Stream stream = ProcessResponse (response);
1233 OnOpenReadCompleted (
1234 new OpenReadCompletedEventArgs (stream, null, false, args [1]));
1235 } catch (ThreadInterruptedException){
1236 if (request != null)
1239 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, null, true, args [1]));
1240 } catch (Exception e){
1241 OnOpenReadCompleted (new OpenReadCompletedEventArgs (null, e, false, args [1]));
1243 object [] cb_args = new object [] {address, userToken};
1244 async_thread.Start (cb_args);
1250 public void OpenWriteAsync (Uri address)
1252 OpenWriteAsync (address, null);
1255 public void OpenWriteAsync (Uri address, string method)
1257 OpenWriteAsync (address, method, null);
1260 public void OpenWriteAsync (Uri address, string method, object userToken)
1262 if (address == null)
1263 throw new ArgumentNullException ("address");
1269 async_thread = new Thread (delegate (object state) {
1270 object [] args = (object []) state;
1271 WebRequest request = null;
1273 request = SetupRequest ((Uri) args [0], (string) args [1], true);
1274 Stream stream = request.GetRequestStream ();
1275 OnOpenWriteCompleted (
1276 new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
1277 } catch (ThreadInterruptedException){
1278 if (request != null)
1280 OnOpenWriteCompleted (
1281 new OpenWriteCompletedEventArgs (null, null, true, args [2]));
1282 } catch (Exception e){
1283 OnOpenWriteCompleted (
1284 new OpenWriteCompletedEventArgs (null, e, false, args [2]));
1286 object [] cb_args = new object [] {address, method, userToken};
1287 async_thread.Start (cb_args);
1293 public void UploadDataAsync (Uri address, byte [] data)
1295 UploadDataAsync (address, null, data);
1298 public void UploadDataAsync (Uri address, string method, byte [] data)
1300 UploadDataAsync (address, method, data, null);
1303 public void UploadDataAsync (Uri address, string method, byte [] data, object userToken)
1305 if (address == null)
1306 throw new ArgumentNullException ("address");
1308 throw new ArgumentNullException ("data");
1314 async_thread = new Thread (delegate (object state) {
1315 object [] args = (object []) state;
1319 data2 = UploadDataCore ((Uri) args [0], (string) args [1], (byte []) args [2], args [3]);
1321 OnUploadDataCompleted (
1322 new UploadDataCompletedEventArgs (data2, null, false, args [3]));
1323 } catch (ThreadInterruptedException){
1324 OnUploadDataCompleted (
1325 new UploadDataCompletedEventArgs (null, null, true, args [3]));
1326 } catch (Exception e){
1327 OnUploadDataCompleted (
1328 new UploadDataCompletedEventArgs (null, e, false, args [3]));
1330 object [] cb_args = new object [] {address, method, data, userToken};
1331 async_thread.Start (cb_args);
1337 public void UploadFileAsync (Uri address, string fileName)
1339 UploadFileAsync (address, null, fileName);
1342 public void UploadFileAsync (Uri address, string method, string fileName)
1344 UploadFileAsync (address, method, fileName, null);
1347 public void UploadFileAsync (Uri address, string method, string fileName, object userToken)
1349 if (address == null)
1350 throw new ArgumentNullException ("address");
1351 if (fileName == null)
1352 throw new ArgumentNullException ("fileName");
1358 async_thread = new Thread (delegate (object state) {
1359 object [] args = (object []) state;
1363 data = UploadFileCore ((Uri) args [0], (string) args [1], (string) args [2], args [3]);
1364 OnUploadFileCompleted (
1365 new UploadFileCompletedEventArgs (data, null, false, args [3]));
1366 } catch (ThreadInterruptedException){
1367 OnUploadFileCompleted (
1368 new UploadFileCompletedEventArgs (null, null, true, args [3]));
1369 } catch (Exception e){
1370 OnUploadFileCompleted (
1371 new UploadFileCompletedEventArgs (null, e, false, args [3]));
1373 object [] cb_args = new object [] {address, method, fileName, userToken};
1374 async_thread.Start (cb_args);
1378 // UploadStringAsync
1380 public void UploadStringAsync (Uri address, string data)
1382 UploadStringAsync (address, null, data);
1385 public void UploadStringAsync (Uri address, string method, string data)
1387 UploadStringAsync (address, method, data, null);
1390 public void UploadStringAsync (Uri address, string method, string data, object userToken)
1392 if (address == null)
1393 throw new ArgumentNullException ("address");
1395 throw new ArgumentNullException ("data");
1401 async_thread = new Thread (delegate (object state) {
1402 object [] args = (object []) state;
1405 string data2 = UploadString ((Uri) args [0], (string) args [1], (string) args [2]);
1406 OnUploadStringCompleted (
1407 new UploadStringCompletedEventArgs (data2, null, false, args [3]));
1408 } catch (ThreadInterruptedException){
1409 OnUploadStringCompleted (
1410 new UploadStringCompletedEventArgs (null, null, true, args [3]));
1411 } catch (Exception e){
1412 OnUploadStringCompleted (
1413 new UploadStringCompletedEventArgs (null, e, false, args [3]));
1415 object [] cb_args = new object [] {address, method, data, userToken};
1416 async_thread.Start (cb_args);
1420 // UploadValuesAsync
1422 public void UploadValuesAsync (Uri address, NameValueCollection values)
1424 UploadValuesAsync (address, null, values);
1427 public void UploadValuesAsync (Uri address, string method, NameValueCollection values)
1429 UploadValuesAsync (address, method, values, null);
1432 public void UploadValuesAsync (Uri address, string method, NameValueCollection values, object userToken)
1434 if (address == null)
1435 throw new ArgumentNullException ("address");
1437 throw new ArgumentNullException ("values");
1443 async_thread = new Thread (delegate (object state) {
1444 object [] args = (object []) state;
1446 byte [] data = UploadValuesCore ((Uri) args [0], (string) args [1], (NameValueCollection) args [2], args [3]);
1447 OnUploadValuesCompleted (
1448 new UploadValuesCompletedEventArgs (data, null, false, args [3]));
1449 } catch (ThreadInterruptedException){
1450 OnUploadValuesCompleted (
1451 new UploadValuesCompletedEventArgs (null, null, true, args [3]));
1452 } catch (Exception e){
1453 OnUploadValuesCompleted (
1454 new UploadValuesCompletedEventArgs (null, e, false, args [3]));
1456 object [] cb_args = new object [] {address, method, values, userToken};
1457 async_thread.Start (cb_args);
1461 protected virtual void OnDownloadDataCompleted (DownloadDataCompletedEventArgs args)
1464 if (DownloadDataCompleted != null)
1465 DownloadDataCompleted (this, args);
1468 protected virtual void OnDownloadFileCompleted (AsyncCompletedEventArgs args)
1471 if (DownloadFileCompleted != null)
1472 DownloadFileCompleted (this, args);
1475 protected virtual void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
1477 if (DownloadProgressChanged != null)
1478 DownloadProgressChanged (this, e);
1481 protected virtual void OnDownloadStringCompleted (DownloadStringCompletedEventArgs args)
1484 if (DownloadStringCompleted != null)
1485 DownloadStringCompleted (this, args);
1488 protected virtual void OnOpenReadCompleted (OpenReadCompletedEventArgs args)
1491 if (OpenReadCompleted != null)
1492 OpenReadCompleted (this, args);
1495 protected virtual void OnOpenWriteCompleted (OpenWriteCompletedEventArgs args)
1498 if (OpenWriteCompleted != null)
1499 OpenWriteCompleted (this, args);
1502 protected virtual void OnUploadDataCompleted (UploadDataCompletedEventArgs args)
1505 if (UploadDataCompleted != null)
1506 UploadDataCompleted (this, args);
1509 protected virtual void OnUploadFileCompleted (UploadFileCompletedEventArgs args)
1512 if (UploadFileCompleted != null)
1513 UploadFileCompleted (this, args);
1516 protected virtual void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
1518 if (UploadProgressChanged != null)
1519 UploadProgressChanged (this, e);
1522 protected virtual void OnUploadStringCompleted (UploadStringCompletedEventArgs args)
1525 if (UploadStringCompleted != null)
1526 UploadStringCompleted (this, args);
1529 protected virtual void OnUploadValuesCompleted (UploadValuesCompletedEventArgs args)
1532 if (UploadValuesCompleted != null)
1533 UploadValuesCompleted (this, args);
1536 [MonoNotSupported("")]
1537 protected virtual WebRequest GetWebRequest (Uri address)
1539 throw new NotImplementedException ();
1542 protected virtual WebResponse GetWebResponse (WebRequest request)
1544 return request.GetResponse ();
1547 protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
1549 return request.EndGetResponse (result);