2 // System.Net.WebClient
\r
5 // Lawrence Pit (loz@cable.a2000.nl)
\r
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
\r
8 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
\r
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections.Specialized;
\r
34 using System.ComponentModel;
\r
36 using System.Runtime.InteropServices;
\r
37 using System.Runtime.Serialization;
\r
40 namespace System.Net
\r
43 public sealed class WebClient : Component
\r
45 static readonly string urlEncodedCType = "application/x-www-form-urlencoded";
\r
46 static byte [] hexBytes;
\r
47 ICredentials credentials;
\r
48 WebHeaderCollection headers;
\r
49 WebHeaderCollection responseHeaders;
\r
52 NameValueCollection queryString;
\r
57 hexBytes = new byte [16];
\r
59 for (int i = '0'; i <= '9'; i++, index++)
\r
60 hexBytes [index] = (byte) i;
\r
62 for (int i = 'A'; i <= 'F'; i++, index++)
\r
63 hexBytes [index] = (byte) i;
\r
72 public string BaseAddress {
\r
74 if (baseString == null) {
\r
75 if (baseAddress == null)
\r
79 baseString = baseAddress.ToString ();
\r
84 if (value == null || value == "") {
\r
87 baseAddress = new Uri (value);
\r
92 public ICredentials Credentials {
\r
93 get { return credentials; }
\r
94 set { credentials = value; }
\r
97 public WebHeaderCollection Headers {
\r
99 if (headers == null)
\r
100 headers = new WebHeaderCollection ();
\r
104 set { headers = value; }
\r
107 public NameValueCollection QueryString {
\r
109 if (queryString == null)
\r
110 queryString = new NameValueCollection ();
\r
112 return queryString;
\r
114 set { queryString = value; }
\r
117 public WebHeaderCollection ResponseHeaders {
\r
118 get { return responseHeaders; }
\r
123 public byte [] DownloadData (string address)
\r
125 WebRequest request = SetupRequest (address);
\r
126 WebResponse response = request.GetResponse ();
\r
127 Stream st = ProcessResponse (response);
\r
128 return ReadAll (st, (int) response.ContentLength);
\r
131 public void DownloadFile (string address, string fileName)
\r
133 WebRequest request = SetupRequest (address);
\r
134 WebResponse response = request.GetResponse ();
\r
135 Stream st = ProcessResponse (response);
\r
137 int cLength = (int) response.ContentLength;
\r
138 int length = (cLength <= -1 || cLength > 8192) ? 8192 : cLength;
\r
139 byte [] buffer = new byte [length];
\r
140 FileStream f = new FileStream (fileName, FileMode.CreateNew);
\r
143 while ((nread = st.Read (buffer, 0, length)) != 0)
\r
144 f.Write (buffer, 0, nread);
\r
149 public Stream OpenRead (string address)
\r
151 WebRequest request = SetupRequest (address);
\r
152 WebResponse response = request.GetResponse ();
\r
153 return ProcessResponse (response);
\r
156 public Stream OpenWrite (string address)
\r
158 return OpenWrite (address, "POST");
\r
161 public Stream OpenWrite (string address, string method)
\r
163 WebRequest request = SetupRequest (address, method);
\r
164 return request.GetRequestStream ();
\r
167 public byte [] UploadData (string address, byte [] data)
\r
169 return UploadData (address, "POST", data);
\r
172 public byte [] UploadData (string address, string method, byte [] data)
\r
175 throw new ArgumentNullException ("data");
\r
177 int contentLength = data.Length;
\r
178 WebRequest request = SetupRequest (address, method, contentLength);
\r
179 using (Stream stream = request.GetRequestStream ()) {
\r
180 stream.Write (data, 0, contentLength);
\r
183 WebResponse response = request.GetResponse ();
\r
184 Stream st = ProcessResponse (response);
\r
185 return ReadAll (st, (int) response.ContentLength);
\r
188 public byte [] UploadFile (string address, string fileName)
\r
190 return UploadFile (address, "POST", fileName);
\r
193 public byte [] UploadFile (string address, string method, string fileName)
\r
195 string fileCType = Headers ["Content-Type"];
\r
196 if (fileCType != null) {
\r
197 string lower = fileCType.ToLower ();
\r
198 if (lower.StartsWith ("multipart/"))
\r
199 throw new WebException ("Content-Type cannot be set to a multipart" +
\r
200 " type for this request.");
\r
202 fileCType = "application/octet-stream";
\r
205 string boundary = "------------" + DateTime.Now.Ticks.ToString ("x");
\r
206 Headers ["Content-Type"] = String.Format ("multipart/form-data; boundary={0}", boundary);
\r
207 WebRequest request = SetupRequest (address, method);
\r
208 Stream reqStream = null;
\r
209 Stream fStream = null;
\r
210 byte [] resultBytes = null;
\r
213 fStream = File.OpenRead (fileName);
\r
214 reqStream = request.GetRequestStream ();
\r
215 byte [] realBoundary = Encoding.ASCII.GetBytes ("--" + boundary + "\r\n");
\r
216 reqStream.Write (realBoundary, 0, realBoundary.Length);
\r
217 string partHeaders = String.Format ("Content-Disposition: form-data; " +
\r
218 "name=\"file\"; filename=\"{0}\"\r\n" +
\r
219 "Content-Type: {1}\r\n\r\n",
\r
220 Path.GetFileName (fileName), fileCType);
\r
222 byte [] partHeadersBytes = Encoding.UTF8.GetBytes (partHeaders);
\r
223 reqStream.Write (partHeadersBytes, 0, partHeadersBytes.Length);
\r
225 byte [] buffer = new byte [4096];
\r
226 while ((nread = fStream.Read (buffer, 0, 4096)) != 0)
\r
227 reqStream.Write (buffer, 0, nread);
\r
229 reqStream.WriteByte ((byte) '\r');
\r
230 reqStream.WriteByte ((byte) '\n');
\r
231 reqStream.Write (realBoundary, 0, realBoundary.Length);
\r
232 reqStream.Close ();
\r
234 WebResponse response = request.GetResponse ();
\r
235 Stream st = ProcessResponse (response);
\r
236 resultBytes = ReadAll (st, (int) response.ContentLength);
\r
237 } catch (WebException) {
\r
239 } catch (Exception e) {
\r
240 throw new WebException ("Error uploading file.", e);
\r
242 if (fStream != null)
\r
245 if (reqStream != null)
\r
246 reqStream.Close ();
\r
249 return resultBytes;
\r
252 public byte[] UploadValues (string address, NameValueCollection data)
\r
254 return UploadValues (address, "POST", data);
\r
257 public byte[] UploadValues (string address, string method, NameValueCollection data)
\r
260 throw new ArgumentNullException ("data"); // MS throws a nullref
\r
262 string cType = Headers ["Content-Type"];
\r
263 if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
\r
264 throw new WebException ("Content-Type header cannot be changed from its default " +
\r
265 "value for this request.");
\r
267 Headers ["Content-Type"] = urlEncodedCType;
\r
268 WebRequest request = SetupRequest (address, method);
\r
269 Stream rqStream = request.GetRequestStream ();
\r
270 MemoryStream tmpStream = new MemoryStream ();
\r
271 foreach (string key in data) {
\r
272 byte [] bytes = Encoding.ASCII.GetBytes (key);
\r
273 UrlEncodeAndWrite (tmpStream, bytes);
\r
274 tmpStream.WriteByte ((byte) '=');
\r
275 bytes = Encoding.ASCII.GetBytes (data [key]);
\r
276 UrlEncodeAndWrite (tmpStream, bytes);
\r
277 tmpStream.WriteByte ((byte) '&');
\r
280 int length = (int) tmpStream.Length;
\r
282 tmpStream.SetLength (--length); // remove trailing '&'
\r
284 tmpStream.WriteByte ((byte) '\r');
\r
285 tmpStream.WriteByte ((byte) '\n');
\r
287 byte [] buf = tmpStream.GetBuffer ();
\r
288 rqStream.Write (buf, 0, length + 2);
\r
290 tmpStream.Close ();
\r
292 WebResponse response = request.GetResponse ();
\r
293 Stream st = ProcessResponse (response);
\r
294 return ReadAll (st, (int) response.ContentLength);
\r
297 Uri MakeUri (string path)
\r
299 string query = null;
\r
300 if (queryString != null && queryString.Count != 0) {
\r
301 // This is not the same as UploadValues, because these 'keys' are not
\r
302 // urlencoded here.
\r
303 StringBuilder sb = new StringBuilder ();
\r
305 foreach (string key in queryString)
\r
306 sb.AppendFormat ("{0}={1}&", key, UrlEncode (queryString [key]));
\r
308 if (sb.Length != 0) {
\r
309 sb.Length--; // remove trailing '&'
\r
310 query = sb.ToString ();
\r
315 if (baseAddress == null && query == null) {
\r
317 return new Uri (path);
\r
319 catch (System.UriFormatException) {
\r
320 if ((path[0] == Path.DirectorySeparatorChar) || (path[1] == ':' && Char.ToLower(path[0]) > 'a' && Char.ToLower(path[0]) < 'z')) {
\r
321 return new Uri ("file://" + path);
\r
324 return new Uri ("file://" + Environment.CurrentDirectory + Path.DirectorySeparatorChar + path);
\r
329 if (baseAddress == null)
\r
330 return new Uri (path + query, (query != null));
\r
333 return new Uri (baseAddress, path);
\r
335 return new Uri (baseAddress, path + query, (query != null));
\r
338 WebRequest SetupRequest (string address)
\r
340 Uri uri = MakeUri (address);
\r
341 WebRequest request = WebRequest.Create (uri);
\r
342 request.Credentials = credentials;
\r
344 // Special headers. These are properties of HttpWebRequest.
\r
345 // What do we do with other requests differnt from HttpWebRequest?
\r
346 if (headers != null && headers.Count != 0 && (request is HttpWebRequest)) {
\r
347 HttpWebRequest req = (HttpWebRequest) request;
\r
348 string expect = headers ["Expect"];
\r
349 string contentType = headers ["Content-Type"];
\r
350 string accept = headers ["Accept"];
\r
351 string connection = headers ["Connection"];
\r
352 string userAgent = headers ["User-Agent"];
\r
353 string referer = headers ["Referer"];
\r
354 headers.RemoveInternal ("Expect");
\r
355 headers.RemoveInternal ("Content-Type");
\r
356 headers.RemoveInternal ("Accept");
\r
357 headers.RemoveInternal ("Connection");
\r
358 headers.RemoveInternal ("Referer");
\r
359 headers.RemoveInternal ("User-Agent");
\r
360 request.Headers = headers;
\r
362 if (expect != null && expect != "")
\r
363 req.Expect = expect;
\r
365 if (accept != null && accept != "")
\r
366 req.Accept = accept;
\r
368 if (contentType != null && contentType != "")
\r
369 req.ContentType = contentType;
\r
371 if (connection != null && connection != "")
\r
372 req.Connection = connection;
\r
374 if (userAgent != null && userAgent != "")
\r
375 req.UserAgent = userAgent;
\r
377 if (referer != null && referer != "")
\r
378 req.Referer = referer;
\r
381 responseHeaders = null;
\r
385 WebRequest SetupRequest (string address, string method)
\r
387 WebRequest request = SetupRequest (address);
\r
388 request.Method = method;
\r
392 WebRequest SetupRequest (string address, string method, int contentLength)
\r
394 WebRequest request = SetupRequest (address, method);
\r
395 request.ContentLength = contentLength;
\r
399 Stream ProcessResponse (WebResponse response)
\r
401 responseHeaders = response.Headers;
\r
402 return response.GetResponseStream ();
\r
405 static byte [] ReadAll (Stream stream, int length)
\r
407 MemoryStream ms = null;
\r
409 bool nolength = (length == -1);
\r
410 int size = ((nolength) ? 8192 : length);
\r
412 ms = new MemoryStream ();
\r
416 byte [] buffer = new byte [size];
\r
417 while ((nread = stream.Read (buffer, offset, size)) != 0) {
\r
419 ms.Write (buffer, 0, nread);
\r
427 return ms.ToArray ();
\r
432 string UrlEncode (string str)
\r
434 StringBuilder result = new StringBuilder ();
\r
436 int len = str.Length;
\r
437 for (int i = 0; i < len; i++) {
\r
440 result.Append ('+');
\r
441 else if ((c < '0' && c != '-' && c != '.') ||
\r
442 (c < 'A' && c > '9') ||
\r
443 (c > 'Z' && c < 'a' && c != '_') ||
\r
445 result.Append ('%');
\r
446 int idx = ((int) c) >> 4;
\r
447 result.Append ((char) hexBytes [idx]);
\r
448 idx = ((int) c) & 0x0F;
\r
449 result.Append ((char) hexBytes [idx]);
\r
455 return result.ToString ();
\r
458 static void UrlEncodeAndWrite (Stream stream, byte [] bytes)
\r
463 int len = bytes.Length;
\r
467 for (int i = 0; i < len; i++) {
\r
468 char c = (char) bytes [i];
\r
470 stream.WriteByte ((byte) '+');
\r
471 else if ((c < '0' && c != '-' && c != '.') ||
\r
472 (c < 'A' && c > '9') ||
\r
473 (c > 'Z' && c < 'a' && c != '_') ||
\r
475 stream.WriteByte ((byte) '%');
\r
476 int idx = ((int) c) >> 4;
\r
477 stream.WriteByte (hexBytes [idx]);
\r
478 idx = ((int) c) & 0x0F;
\r
479 stream.WriteByte (hexBytes [idx]);
\r
481 stream.WriteByte ((byte) c);
\r