2 // HttpWebRequestTest.cs - NUnit Test Cases for System.Net.HttpWebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Martin Willemoes Hansen (mwh@sysrq.dk)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // Andres G. Aragoneses (andres@7digital.com)
9 // Bogdanov Kirill (bogdanov@macroscop.com)
11 // (C) 2003 Martin Willemoes Hansen
12 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com
13 // Copyright (c) 2013 7digital Media Ltd (http://www.7digital.com)
16 using NUnit.Framework;
18 using System.Collections;
19 using System.Collections.Specialized;
20 using System.Globalization;
23 using System.Net.Sockets;
24 using System.Security.Cryptography;
25 using System.Security.Cryptography.X509Certificates;
27 using System.Threading;
28 using System.Reflection;
29 using Mono.Security.Authenticode;
31 using Mono.Security.Protocol.Tls;
34 using MonoTests.Helpers;
36 namespace MonoTests.System.Net
39 public class HttpWebRequestTest
41 private Random rand = new Random ();
42 private byte [] data64KB = new byte [64 * 1024];
47 ServicePointManager.Expect100Continue = false;
48 rand.NextBytes (data64KB);
52 public void Proxy_Null ()
54 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
55 Assert.IsNotNull (req.Proxy, "#1");
57 Assert.IsNull (req.Proxy, "#2");
61 [Category("InetAccess")]
64 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
65 Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
67 req.UserAgent = "MonoClient v1.0";
68 Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
69 Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
71 HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
72 Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
73 Assert.AreEqual ("OK", res.StatusDescription, "#B2");
75 Assert.IsTrue (res.Headers.Get ("Content-Type").StartsWith ("text/html; charset=", StringComparison.OrdinalIgnoreCase), "#C1");
76 Assert.IsNotNull (res.LastModified, "#C2");
77 Assert.AreEqual (0, res.Cookies.Count, "#C3");
83 public void AddRange ()
85 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
87 req.AddRange (50, 90);
88 req.AddRange ("bytes", 100);
89 req.AddRange ("bytes", 100, 120);
90 Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
92 req.AddRange ("bits", 2000);
94 } catch (InvalidOperationException) {}
98 public void CloseRequestStreamAfterReadingResponse ()
100 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
101 string url = "http://" + ep.ToString () + "/test/";
103 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
106 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
109 req.ReadWriteTimeout = 2000;
111 byte [] data = new byte [128];
112 req.ContentLength = data.Length;
114 Stream rs = req.GetRequestStream ();
115 rs.Write (data, 0, data.Length);
118 HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
128 //[Category("InetAccess")]
129 [Category ("NotWorking")] // Disabled until a server that meets requirements is found
130 public void Cookies1 ()
132 // The purpose of this test is to ensure that the cookies we get from a request
133 // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
134 // in HttpWebRequest.
135 // If this URL stops sending *one* and only one cookie, replace it.
136 string url = "http://xamarin.com";
137 CookieContainer cookies = new CookieContainer ();
138 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
139 req.KeepAlive = false;
140 req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
141 req.CookieContainer = cookies;
142 Assert.AreEqual (0, cookies.Count, "#01");
143 using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
144 CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
145 Assert.AreEqual (1, coll.Count, "#02");
146 Assert.AreEqual (1, res.Cookies.Count, "#03");
147 Cookie one = coll [0];
148 Cookie two = res.Cookies [0];
149 Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
155 [Ignore ("Fails on MS.NET")]
156 public void SslClientBlock ()
158 // This tests that the write request/initread/write body sequence does not hang
160 // If there's a regression for this, the test will hang.
161 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
163 SslHttpServer server = new SslHttpServer ();
166 string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
167 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
168 request.Method = "POST";
169 Stream stream = request.GetRequestStream ();
170 byte [] bytes = new byte [100];
171 stream.Write (bytes, 0, bytes.Length);
173 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
174 Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
175 StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
180 if (server.Error != null)
183 ServicePointManager.CertificatePolicy = null;
188 public void Missing_ContentEncoding ()
190 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
192 BadChunkedServer server = new BadChunkedServer ();
195 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
196 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
197 request.Method = "GET";
198 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
199 Assert.AreEqual ("", resp.ContentEncoding);
202 if (server.Error != null)
205 ServicePointManager.CertificatePolicy = null;
210 public void BadServer_ChunkedClose ()
212 // The server will send a chunked response without a 'last-chunked' mark
213 // and then shutdown the socket for sending.
214 BadChunkedServer server = new BadChunkedServer ();
216 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
217 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
218 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
221 byte [] bytes = new byte [32];
222 // Using StreamReader+UTF8Encoding here fails on MS runtime
223 Stream stream = resp.GetResponseStream ();
224 int nread = stream.Read (bytes, 0, 32);
225 Assert.AreEqual (16, nread, "#01");
226 x = Encoding.ASCII.GetString (bytes, 0, 16);
232 if (server.Error != null)
235 Assert.AreEqual ("1234567890123456", x);
239 [Ignore ("This test asserts that our code violates RFC 2616")]
240 public void MethodCase ()
242 ListDictionary methods = new ListDictionary ();
243 methods.Add ("post", "POST");
244 methods.Add ("puT", "PUT");
245 methods.Add ("POST", "POST");
246 methods.Add ("whatever", "whatever");
247 methods.Add ("PUT", "PUT");
249 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
250 string url = "http://" + ep.ToString () + "/test/";
252 foreach (DictionaryEntry de in methods) {
253 SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler));
256 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
257 req.Method = (string) de.Key;
259 req.ReadWriteTimeout = 2000;
260 req.KeepAlive = false;
261 Stream rs = req.GetRequestStream ();
263 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
264 StreamReader sr = new StreamReader (resp.GetResponseStream (),
266 string line = sr.ReadLine ();
268 Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
277 public void BeginGetRequestStream_Body_NotAllowed ()
279 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
280 string url = "http://" + ep.ToString () + "/test/";
282 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
285 HttpWebRequest request;
287 request = (HttpWebRequest) WebRequest.Create (url);
288 request.Method = "GET";
291 request.BeginGetRequestStream (null, null);
293 } catch (ProtocolViolationException ex) {
294 // Cannot send a content-body with this
296 Assert.IsNull (ex.InnerException, "#A2");
297 Assert.IsNotNull (ex.Message, "#A3");
300 request = (HttpWebRequest) WebRequest.Create (url);
301 request.Method = "HEAD";
304 request.BeginGetRequestStream (null, null);
306 } catch (ProtocolViolationException ex) {
307 // Cannot send a content-body with this
309 Assert.IsNull (ex.InnerException, "#B2");
310 Assert.IsNotNull (ex.Message, "#B3");
315 [Test] // bug #465613
316 public void BeginGetRequestStream_NoBuffering ()
318 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
319 string url = "http://" + ep.ToString () + "/test/";
321 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
328 req = (HttpWebRequest) WebRequest.Create (url);
330 req.SendChunked = false;
331 req.KeepAlive = false;
332 req.AllowWriteStreamBuffering = false;
334 ar = req.BeginGetRequestStream (null, null);
335 rs = req.EndGetRequestStream (ar);
338 req = (HttpWebRequest) WebRequest.Create (url);
340 req.SendChunked = false;
341 req.KeepAlive = true;
342 req.AllowWriteStreamBuffering = false;
345 req.BeginGetRequestStream (null, null);
347 } catch (ProtocolViolationException ex) {
348 // When performing a write operation with
349 // AllowWriteStreamBuffering set to false,
350 // you must either set ContentLength to a
351 // non-negative number or set SendChunked
353 Assert.IsNull (ex.InnerException, "#A2");
354 Assert.IsNotNull (ex.Message, "#A3");
357 req = (HttpWebRequest) WebRequest.Create (url);
359 req.SendChunked = false;
360 req.KeepAlive = true;
361 req.AllowWriteStreamBuffering = false;
362 req.ContentLength = 0;
364 ar = req.BeginGetRequestStream (null, null);
365 rs = req.EndGetRequestStream (ar);
370 [Test] // bug #508027
371 [Category ("NotWorking")] // #5842
372 public void BeginGetResponse ()
374 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
375 string url = "http://" + ep.ToString () + "/test/";
377 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
382 req = (HttpWebRequest) WebRequest.Create (url);
385 req.SendChunked = false;
386 req.KeepAlive = false;
387 req.AllowWriteStreamBuffering = false;
388 req.BeginGetResponse (null, null);
391 req = (HttpWebRequest) WebRequest.Create (url);
394 req.SendChunked = true;
395 req.KeepAlive = false;
396 req.AllowWriteStreamBuffering = false;
397 req.GetRequestStream ().WriteByte (1);
398 req.BeginGetResponse (null, null);
401 req = (HttpWebRequest) WebRequest.Create (url);
404 req.ContentLength = 5;
405 req.SendChunked = false;
406 req.KeepAlive = false;
407 req.AllowWriteStreamBuffering = false;
408 req.GetRequestStream ().WriteByte (5);
409 req.BeginGetResponse (null, null);
412 req = (HttpWebRequest) WebRequest.Create (url);
415 req.SendChunked = false;
416 req.KeepAlive = true;
417 req.AllowWriteStreamBuffering = false;
419 req.BeginGetResponse (null, null);
422 req = (HttpWebRequest) WebRequest.Create (url);
425 req.SendChunked = false;
426 req.KeepAlive = false;
427 req.AllowWriteStreamBuffering = false;
428 req.ContentLength = 5;
429 req.BeginGetResponse (null, null);
432 req = (HttpWebRequest) WebRequest.Create (url);
435 req.SendChunked = false;
436 req.KeepAlive = true;
437 req.AllowWriteStreamBuffering = false;
438 req.ContentLength = 5;
439 req.BeginGetResponse (null, null);
442 req = (HttpWebRequest) WebRequest.Create (url);
445 req.SendChunked = true;
447 req.BeginGetResponse (null, null);
450 req = (HttpWebRequest) WebRequest.Create (url);
453 req.ContentLength = 5;
455 req.BeginGetResponse (null, null);
458 req = (HttpWebRequest) WebRequest.Create (url);
461 req.ContentLength = 0;
463 req.BeginGetResponse (null, null);
468 [Test] // bug #511851
469 public void BeginGetRequestStream_Request_Aborted ()
471 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
472 string url = "http://" + ep.ToString () + "/test/";
474 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
477 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
482 req.BeginGetRequestStream (null, null);
484 } catch (WebException ex) {
485 // The request was aborted: The request was canceled
486 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
487 Assert.IsNull (ex.InnerException, "#3");
488 Assert.IsNotNull (ex.Message, "#4");
489 Assert.IsNull (ex.Response, "#5");
490 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
495 [Test] // bug #511851
496 public void BeginGetResponse_Request_Aborted ()
498 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
499 string url = "http://" + ep.ToString () + "/test/";
501 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
504 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
509 req.BeginGetResponse (null, null);
511 } catch (WebException ex) {
512 // The request was aborted: The request was canceled
513 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
514 Assert.IsNull (ex.InnerException, "#3");
515 Assert.IsNotNull (ex.Message, "#4");
516 Assert.IsNull (ex.Response, "#5");
517 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
523 public void EndGetRequestStream_AsyncResult_Null ()
525 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
526 string url = "http://" + ep.ToString () + "/test/";
528 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
531 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
533 req.BeginGetRequestStream (null, null);
536 req.EndGetRequestStream (null);
538 } catch (ArgumentNullException ex) {
539 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
540 Assert.IsNull (ex.InnerException, "#3");
541 Assert.IsNotNull (ex.Message, "#4");
542 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
550 [Category ("NotWorking")] // do not get consistent result on MS
551 public void EndGetRequestStream_Request_Aborted ()
553 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
554 string url = "http://" + ep.ToString () + "/test/";
556 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
559 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
561 IAsyncResult ar = req.BeginGetRequestStream (null, null);
566 req.EndGetRequestStream (ar);
568 } catch (WebException ex) {
569 // The request was aborted: The request was canceled
570 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
571 Assert.IsNull (ex.InnerException, "#3");
572 Assert.IsNotNull (ex.Message, "#4");
573 Assert.IsNull (ex.Response, "#5");
574 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
579 [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
580 [Category ("NotWorking")]
581 public void EndGetResponse_AsyncResult_Invalid ()
583 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
584 string url = "http://" + ep.ToString () + "/test/";
586 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
589 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
592 req.ReadWriteTimeout = 2000;
593 IAsyncResult ar = req.BeginGetRequestStream (null, null);
595 // AsyncResult was not returned from call to BeginGetResponse
597 req.EndGetResponse (ar);
599 } catch (InvalidCastException) {
607 public void EndGetResponse_AsyncResult_Null ()
609 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
610 string url = "http://" + ep.ToString () + "/test/";
612 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
615 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
617 req.ReadWriteTimeout = 2000;
619 IAsyncResult ar = req.BeginGetResponse (null, null);
622 req.EndGetResponse (null);
624 } catch (ArgumentNullException ex) {
625 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
626 Assert.IsNull (ex.InnerException, "#3");
627 Assert.IsNotNull (ex.Message, "#4");
628 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
632 using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
639 [Test] // bug #429200
640 public void GetRequestStream ()
642 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
643 string url = "http://" + ep.ToString () + "/test/";
645 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
648 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
651 req.ReadWriteTimeout = 2000;
653 Stream rs1 = req.GetRequestStream ();
654 Stream rs2 = req.GetRequestStream ();
656 Assert.IsNotNull (rs1, "#1");
657 Assert.AreSame (rs1, rs2, "#2");
663 [Test] // bug #511851
664 public void GetRequestStream_Request_Aborted ()
666 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
667 string url = "http://" + ep.ToString () + "/test/";
669 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
672 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
677 req.GetRequestStream ();
679 } catch (WebException ex) {
680 // The request was aborted: The request was canceled
681 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
682 Assert.IsNull (ex.InnerException, "#3");
683 Assert.IsNotNull (ex.Message, "#4");
684 Assert.IsNull (ex.Response, "#5");
685 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
690 [Test] // bug #510661
691 [Category ("NotWorking")] // #5842
692 public void GetRequestStream_Close_NotAllBytesWritten ()
694 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
695 string url = "http://" + ep.ToString () + "/test/";
697 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
703 req = (HttpWebRequest) WebRequest.Create (url);
705 req.ContentLength = 2;
706 rs = req.GetRequestStream ();
710 } catch (WebException ex) {
711 // The request was aborted: The request was canceled
712 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
713 Assert.IsNotNull (ex.Message, "#A3");
714 Assert.IsNull (ex.Response, "#A4");
715 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
717 // Cannot close stream until all bytes are written
718 Exception inner = ex.InnerException;
719 Assert.IsNotNull (inner, "#A6");
720 Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
721 Assert.IsNull (inner.InnerException, "#A8");
722 Assert.IsNotNull (inner.Message, "#A9");
725 req = (HttpWebRequest) WebRequest.Create (url);
727 req.ContentLength = 2;
728 rs = req.GetRequestStream ();
733 } catch (WebException ex) {
734 // The request was aborted: The request was canceled
735 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
736 Assert.IsNotNull (ex.Message, "#B3");
737 Assert.IsNull (ex.Response, "#B4");
738 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
740 // Cannot close stream until all bytes are written
741 Exception inner = ex.InnerException;
742 Assert.IsNotNull (inner, "#B6");
743 Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
744 Assert.IsNull (inner.InnerException, "#B8");
745 Assert.IsNotNull (inner.Message, "#B9");
748 req = (HttpWebRequest) WebRequest.Create (url);
750 req.ContentLength = 2;
751 rs = req.GetRequestStream ();
758 [Test] // bug #510642
759 [Category ("NotWorking")] // #5842
760 public void GetRequestStream_Write_Overflow ()
762 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
763 string url = "http://" + ep.ToString () + "/test/";
765 // buffered, non-chunked
766 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
773 req = (HttpWebRequest) WebRequest.Create (url);
776 req.ReadWriteTimeout = 2000;
777 req.ContentLength = 2;
779 rs = req.GetRequestStream ();
782 buffer = new byte [] { 0x2a, 0x1d };
784 rs.Write (buffer, 0, buffer.Length);
786 } catch (ProtocolViolationException ex) {
787 // Bytes to be written to the stream exceed
788 // Content-Length bytes size specified
789 Assert.IsNull (ex.InnerException, "#A2");
790 Assert.IsNotNull (ex.Message, "#A3");
795 req = (HttpWebRequest) WebRequest.Create (url);
798 req.ReadWriteTimeout = 2000;
799 req.ContentLength = 2;
801 rs = req.GetRequestStream ();
803 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
805 rs.Write (buffer, 0, buffer.Length);
807 } catch (ProtocolViolationException ex) {
808 // Bytes to be written to the stream exceed
809 // Content-Length bytes size specified
810 Assert.IsNull (ex.InnerException, "#B2");
811 Assert.IsNotNull (ex.Message, "#B3");
818 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
826 req = (HttpWebRequest) WebRequest.Create (url);
828 req.SendChunked = true;
830 req.ReadWriteTimeout = 2000;
831 req.ContentLength = 2;
833 rs = req.GetRequestStream ();
836 buffer = new byte [] { 0x2a, 0x1d };
837 rs.Write (buffer, 0, buffer.Length);
841 req = (HttpWebRequest) WebRequest.Create (url);
843 req.SendChunked = true;
845 req.ReadWriteTimeout = 2000;
846 req.ContentLength = 2;
848 rs = req.GetRequestStream ();
850 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
851 rs.Write (buffer, 0, buffer.Length);
855 // non-buffered, non-chunked
856 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
863 req = (HttpWebRequest) WebRequest.Create (url);
864 req.AllowWriteStreamBuffering = false;
867 req.ReadWriteTimeout = 2000;
868 req.ContentLength = 2;
870 rs = req.GetRequestStream ();
873 buffer = new byte [] { 0x2a, 0x1d };
875 rs.Write (buffer, 0, buffer.Length);
877 } catch (ProtocolViolationException ex) {
878 // Bytes to be written to the stream exceed
879 // Content-Length bytes size specified
880 Assert.IsNull (ex.InnerException, "#C2");
881 Assert.IsNotNull (ex.Message, "#3");
886 req = (HttpWebRequest) WebRequest.Create (url);
887 req.AllowWriteStreamBuffering = false;
890 req.ReadWriteTimeout = 2000;
891 req.ContentLength = 2;
893 rs = req.GetRequestStream ();
895 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
897 rs.Write (buffer, 0, buffer.Length);
899 } catch (ProtocolViolationException ex) {
900 // Bytes to be written to the stream exceed
901 // Content-Length bytes size specified
902 Assert.IsNull (ex.InnerException, "#D2");
903 Assert.IsNotNull (ex.Message, "#D3");
909 // non-buffered, chunked
910 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
917 req = (HttpWebRequest) WebRequest.Create (url);
918 req.AllowWriteStreamBuffering = false;
920 req.SendChunked = true;
922 req.ReadWriteTimeout = 2000;
923 req.ContentLength = 2;
925 rs = req.GetRequestStream ();
928 buffer = new byte [] { 0x2a, 0x1d };
929 rs.Write (buffer, 0, buffer.Length);
932 req = (HttpWebRequest) WebRequest.Create (url);
933 req.AllowWriteStreamBuffering = false;
935 req.SendChunked = true;
937 req.ReadWriteTimeout = 2000;
938 req.ContentLength = 2;
940 rs = req.GetRequestStream ();
942 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
943 rs.Write (buffer, 0, buffer.Length);
949 [Ignore ("This test asserts that our code violates RFC 2616")]
950 public void GetRequestStream_Body_NotAllowed ()
952 string [] methods = new string [] { "GET", "HEAD", "CONNECT",
953 "get", "HeAd", "ConNect" };
955 foreach (string method in methods) {
956 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
957 "http://localhost:8000");
960 req.GetRequestStream ();
961 Assert.Fail ("#1:" + method);
962 } catch (ProtocolViolationException ex) {
963 Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
964 Assert.IsNull (ex.InnerException, "#3:" + method);
965 Assert.IsNotNull (ex.Message, "#4:" + method);
970 [Test] // bug #511851
971 public void GetResponse_Request_Aborted ()
973 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
974 string url = "http://" + ep.ToString () + "/test/";
976 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
979 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
986 } catch (WebException ex) {
987 // The request was aborted: The request was canceled
988 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
989 Assert.IsNull (ex.InnerException, "#3");
990 Assert.IsNotNull (ex.Message, "#4");
991 Assert.IsNull (ex.Response, "#5");
992 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
998 [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
999 public void ReadTimeout ()
1001 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
1002 string url = "http://" + localEP.ToString () + "/original/";
1004 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1007 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1008 req.Method = "POST";
1009 req.AllowAutoRedirect = false;
1011 req.ReadWriteTimeout = 2000;
1012 req.KeepAlive = false;
1013 Stream rs = req.GetRequestStream ();
1015 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1017 Stream s = resp.GetResponseStream ();
1020 } catch (WebException ex) {
1021 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
1022 Assert.IsNull (ex.InnerException, "#3");
1023 Assert.IsNull (ex.Response, "#4");
1024 Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
1031 [Test] // bug #324300
1032 public void AllowAutoRedirect ()
1034 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8765);
1035 string url = "http://" + localEP.ToString () + "/original/";
1037 // allow autoredirect
1038 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1041 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1042 req.Method = "POST";
1044 req.ReadWriteTimeout = 2000;
1045 req.KeepAlive = false;
1046 Stream rs = req.GetRequestStream ();
1048 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1049 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1051 string body = sr.ReadToEnd ();
1053 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1054 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1055 localEP.ToString () + "/moved/", "#A2");
1056 Assert.AreEqual ("GET", resp.Method, "#A3");
1057 Assert.AreEqual ("LOOKS OK", body, "#A4");
1062 // do not allow autoredirect
1063 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1066 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1067 req.Method = "POST";
1068 req.AllowAutoRedirect = false;
1070 req.ReadWriteTimeout = 1000;
1071 req.KeepAlive = false;
1072 Stream rs = req.GetRequestStream ();
1074 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1075 Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
1076 Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
1077 Assert.AreEqual ("POST", resp.Method, "#B3");
1084 public void PostAndRedirect_NoCL ()
1086 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8769);
1087 string url = "http://" + localEP.ToString () + "/original/";
1089 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1092 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1093 req.Method = "POST";
1095 req.ReadWriteTimeout = 2000;
1096 Stream rs = req.GetRequestStream ();
1099 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1100 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1102 string body = sr.ReadToEnd ();
1104 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1105 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1106 localEP.ToString () + "/moved/", "#A2");
1107 Assert.AreEqual ("GET", resp.Method, "#A3");
1108 Assert.AreEqual ("LOOKS OK", body, "#A4");
1115 public void PostAndRedirect_CL ()
1117 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8770);
1118 string url = "http://" + localEP.ToString () + "/original/";
1120 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1123 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1124 req.Method = "POST";
1126 req.ReadWriteTimeout = 2000;
1127 req.ContentLength = 1;
1128 Stream rs = req.GetRequestStream ();
1130 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1131 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1133 string body = sr.ReadToEnd ();
1135 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1136 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1137 localEP.ToString () + "/moved/", "#A2");
1138 Assert.AreEqual ("GET", resp.Method, "#A3");
1139 Assert.AreEqual ("LOOKS OK", body, "#A4");
1146 public void PostAnd401 ()
1148 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8771);
1149 string url = "http://" + localEP.ToString () + "/original/";
1151 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1154 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1155 req.Method = "POST";
1157 req.ReadWriteTimeout = 2000;
1158 req.ContentLength = 1;
1159 Stream rs = req.GetRequestStream ();
1161 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1162 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1164 string body = sr.ReadToEnd ();
1166 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1167 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1168 localEP.ToString () + "/moved/", "#A2");
1169 Assert.AreEqual ("GET", resp.Method, "#A3");
1170 Assert.AreEqual ("LOOKS OK", body, "#A4");
1176 [Test] // bug #324347
1177 [Category ("NotWorking")]
1178 public void InternalServerError ()
1180 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8766);
1181 string url = "http://" + localEP.ToString () + "/original/";
1184 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1187 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1188 req.Method = "POST";
1190 req.ReadWriteTimeout = 2000;
1191 req.KeepAlive = false;
1192 Stream rs = req.GetRequestStream ();
1197 Assert.Fail ("#A1");
1198 } catch (WebException ex) {
1199 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1200 Assert.IsNull (ex.InnerException, "#A3");
1201 Assert.IsNotNull (ex.Message, "#A4");
1202 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
1204 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1205 Assert.IsNotNull (webResponse, "#A6");
1206 Assert.AreEqual ("POST", webResponse.Method, "#A7");
1207 webResponse.Close ();
1214 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1217 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1220 req.ReadWriteTimeout = 2000;
1221 req.KeepAlive = false;
1225 Assert.Fail ("#B1");
1226 } catch (WebException ex) {
1227 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1228 Assert.IsNull (ex.InnerException, "#B3");
1229 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1231 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1232 Assert.IsNotNull (webResponse, "#B5");
1233 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1234 webResponse.Close ();
1242 [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
1243 public void NoContentLength ()
1245 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8767);
1246 string url = "http://" + localEP.ToString () + "/original/";
1249 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1252 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1253 req.Method = "POST";
1255 req.ReadWriteTimeout = 2000;
1256 req.KeepAlive = false;
1257 Stream rs = req.GetRequestStream ();
1262 Assert.Fail ("#A1");
1263 } catch (WebException ex) {
1264 // The underlying connection was closed:
1265 // An unexpected error occurred on a
1267 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1268 Assert.IsNotNull (ex.InnerException, "#A3");
1269 Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
1270 Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
1272 // Unable to read data from the transport connection:
1273 // A connection attempt failed because the connected party
1274 // did not properly respond after a period of time, or
1275 // established connection failed because connected host has
1276 // failed to respond
1277 IOException ioe = (IOException) ex.InnerException;
1278 Assert.IsNotNull (ioe.InnerException, "#A6");
1279 Assert.IsNotNull (ioe.Message, "#A7");
1280 Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
1282 // An existing connection was forcibly
1283 // closed by the remote host
1284 SocketException soe = (SocketException) ioe.InnerException;
1285 Assert.IsNull (soe.InnerException, "#A9");
1286 Assert.IsNotNull (soe.Message, "#A10");
1288 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1289 Assert.IsNull (webResponse, "#A11");
1296 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1299 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1302 req.ReadWriteTimeout = 2000;
1303 req.KeepAlive = false;
1307 Assert.Fail ("#B1");
1308 } catch (WebException ex) {
1309 // The remote server returned an error:
1310 // (500) Internal Server Error
1311 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1312 Assert.IsNull (ex.InnerException, "#B3");
1313 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1315 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1316 Assert.IsNotNull (webResponse, "#B5");
1317 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1318 webResponse.Close ();
1325 [Test] // bug #513087
1326 public void NonStandardVerb ()
1328 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
1329 string url = "http://" + ep.ToString () + "/moved/";
1331 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (VerbEchoHandler))) {
1334 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1335 req.Method = "WhatEver";
1336 req.KeepAlive = false;
1337 req.Timeout = 20000;
1338 req.ReadWriteTimeout = 20000;
1340 Stream rs = req.GetRequestStream ();
1343 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1344 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1346 string body = sr.ReadToEnd ();
1348 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
1349 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1350 ep.ToString () + "/moved/", "#2");
1351 Assert.AreEqual ("WhatEver", resp.Method, "#3");
1352 Assert.AreEqual ("WhatEver", body, "#4");
1360 [Category ("NotWorking")] // Assert #2 fails
1361 public void NotModifiedSince ()
1363 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
1364 string url = "http://" + ep.ToString () + "/test/";
1366 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (NotModifiedSinceHandler))) {
1369 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1371 req.KeepAlive = false;
1372 req.Timeout = 20000;
1373 req.ReadWriteTimeout = 20000;
1374 req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
1375 req.IfModifiedSince = new DateTime (2010, 01, 04);
1377 DateTime start = DateTime.Now;
1378 HttpWebResponse response = null;
1383 } catch (WebException e) {
1384 response = (HttpWebResponse) e.Response;
1387 Assert.IsNotNull (response, "#2");
1388 using (Stream stream = response.GetResponseStream ()) {
1389 byte [] buffer = new byte [4096];
1390 int bytesRead = stream.Read (buffer, 0, buffer.Length);
1391 Assert.AreEqual (0, bytesRead, "#3");
1394 TimeSpan elapsed = DateTime.Now - start;
1395 Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
1401 [Test] // bug #353495
1402 [Category ("NotWorking")]
1403 public void LastModifiedKind ()
1405 const string reqURL = "http://coffeefaq.com/site/node/25";
1406 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
1407 HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
1408 DateTime lastMod = resp.LastModified;
1409 //string rawLastMod = resp.Headers ["Last-Modified"];
1411 //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
1412 Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
1413 req = (HttpWebRequest) WebRequest.Create (reqURL);
1414 req.IfModifiedSince = lastMod;
1416 resp = (HttpWebResponse) req.GetResponse ();
1418 Assert.Fail ("Should result in 304");
1419 } catch (WebException ex) {
1420 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
1421 Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
1426 #region Timeout_Bug // https://bugzilla.novell.com/show_bug.cgi?id=317553
1428 class TimeoutTestHelper {
1431 internal DateTime? Start { get; private set; }
1432 internal DateTime? End { get; private set; }
1433 internal Exception Exception { get; private set; }
1434 internal string Body { get; private set; }
1435 internal int TimeOutInMilliSeconds { get; private set; }
1437 internal TimeoutTestHelper (string url, int timeoutInMilliseconds)
1440 TimeOutInMilliSeconds = timeoutInMilliseconds;
1443 internal void LaunchWebRequest ()
1445 var req = (HttpWebRequest) WebRequest.Create (url_to_test);
1446 req.Timeout = TimeOutInMilliSeconds;
1448 Start = DateTime.Now;
1450 using (var resp = (HttpWebResponse) req.GetResponse ())
1452 var sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
1453 Body = sr.ReadToEnd ();
1455 } catch (Exception e) {
1462 void TestTimeOut (string url, WebExceptionStatus expectedExceptionStatus)
1464 var timeoutWorker = new TimeoutTestHelper (url, three_seconds_in_milliseconds);
1465 var threadStart = new ThreadStart (timeoutWorker.LaunchWebRequest);
1466 var thread = new Thread (threadStart);
1468 Thread.Sleep (three_seconds_in_milliseconds * 3);
1470 if (timeoutWorker.End == null) {
1472 Assert.Fail ("Thread finished after triple the timeout specified has passed");
1475 if (!String.IsNullOrEmpty (timeoutWorker.Body)) {
1476 if (timeoutWorker.Body == response_of_timeout_handler) {
1477 Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve proper body");
1479 Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve an incorrect body: " + timeoutWorker.Body);
1482 Assert.IsNotNull (timeoutWorker.Exception, "Exception was not thrown");
1484 var webEx = timeoutWorker.Exception as WebException;
1485 Assert.IsNotNull (webEx, "Exception thrown should be WebException, but was: " +
1486 timeoutWorker.Exception.GetType ().FullName);
1488 Assert.AreEqual (expectedExceptionStatus, webEx.Status,
1489 "WebException was thrown, but with a wrong status (should be " + expectedExceptionStatus + "): " + webEx.Status);
1491 Assert.IsFalse (timeoutWorker.End > (timeoutWorker.Start + TimeSpan.FromMilliseconds (three_seconds_in_milliseconds + 500)),
1492 "Timeout exception should have been thrown shortly after timeout is reached, however it was at least half-second late");
1495 [Test] // 1st possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
1496 public void TestTimeoutPropertyWithServerThatExistsAndRespondsButTooLate ()
1498 var ep = new IPEndPoint (IPAddress.Loopback, 8123);
1499 string url = "http://" + ep + "/foobar/";
1501 using (var responder = new SocketResponder (ep, TimeOutHandler))
1505 TestTimeOut (url, WebExceptionStatus.Timeout);
1511 [Test] // 2nd possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
1512 public void TestTimeoutWithEndpointThatDoesntExistThrowsConnectFailureBeforeTimeout ()
1514 string url = "http://127.0.0.1:8271/"; // some endpoint that is unlikely to exist
1516 // connecting to a non-existing endpoint should throw a ConnectFailure before the timeout is reached
1517 TestTimeOut (url, WebExceptionStatus.ConnectFailure);
1520 const string response_of_timeout_handler = "RESPONSE_OF_TIMEOUT_HANDLER";
1521 const int three_seconds_in_milliseconds = 3000;
1523 private static byte[] TimeOutHandler (Socket socket)
1525 socket.Receive (new byte[4096]);
1527 Thread.Sleep (three_seconds_in_milliseconds * 2);
1529 var sw = new StringWriter ();
1530 sw.WriteLine ("HTTP/1.1 200 OK");
1531 sw.WriteLine ("Content-Type: text/plain");
1532 sw.WriteLine ("Content-Length: " + response_of_timeout_handler.Length);
1534 sw.Write (response_of_timeout_handler);
1537 return Encoding.UTF8.GetBytes (sw.ToString ());
1542 internal static byte [] EchoRequestHandler (Socket socket)
1544 MemoryStream ms = new MemoryStream ();
1545 byte [] buffer = new byte [4096];
1546 int bytesReceived = socket.Receive (buffer);
1547 while (bytesReceived > 0) {
1548 ms.Write (buffer, 0, bytesReceived);
1549 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1550 // after sending the headers
1552 if (socket.Available > 0) {
1553 bytesReceived = socket.Receive (buffer);
1560 StreamReader sr = new StreamReader (ms, Encoding.UTF8);
1561 string request = sr.ReadToEnd ();
1563 StringWriter sw = new StringWriter ();
1564 sw.WriteLine ("HTTP/1.1 200 OK");
1565 sw.WriteLine ("Content-Type: text/xml");
1566 sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
1571 return Encoding.UTF8.GetBytes (sw.ToString ());
1574 static byte [] RedirectRequestHandler (Socket socket)
1576 MemoryStream ms = new MemoryStream ();
1577 byte [] buffer = new byte [4096];
1578 int bytesReceived = socket.Receive (buffer);
1579 while (bytesReceived > 0) {
1580 ms.Write (buffer, 0, bytesReceived);
1581 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1582 // after sending the headers
1584 if (socket.Available > 0) {
1585 bytesReceived = socket.Receive (buffer);
1592 string statusLine = null;
1593 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1594 statusLine = sr.ReadLine ();
1597 StringWriter sw = new StringWriter ();
1598 if (statusLine.StartsWith ("POST /original/")) {
1599 sw.WriteLine ("HTTP/1.0 302 Found");
1600 EndPoint ep = socket.LocalEndPoint;
1601 sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
1604 } else if (statusLine.StartsWith ("GET /moved/")) {
1605 sw.WriteLine ("HTTP/1.0 200 OK");
1606 sw.WriteLine ("Content-Type: text/plain");
1607 sw.WriteLine ("Content-Length: 8");
1609 sw.Write ("LOOKS OK");
1612 sw.WriteLine ("HTTP/1.0 500 Too Lazy");
1617 return Encoding.UTF8.GetBytes (sw.ToString ());
1620 static byte [] InternalErrorHandler (Socket socket)
1622 byte [] buffer = new byte [4096];
1623 int bytesReceived = socket.Receive (buffer);
1624 while (bytesReceived > 0) {
1625 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1626 // after sending the headers
1628 if (socket.Available > 0) {
1629 bytesReceived = socket.Receive (buffer);
1634 StringWriter sw = new StringWriter ();
1635 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1636 sw.WriteLine ("Content-Length: 0");
1640 return Encoding.UTF8.GetBytes (sw.ToString ());
1643 static byte [] NoContentLengthHandler (Socket socket)
1645 StringWriter sw = new StringWriter ();
1646 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1650 return Encoding.UTF8.GetBytes (sw.ToString ());
1653 static byte [] NotModifiedSinceHandler (Socket socket)
1655 StringWriter sw = new StringWriter ();
1656 sw.WriteLine ("HTTP/1.1 304 Not Modified");
1657 sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
1658 sw.WriteLine ("Server: Apache/2.2.6 (Debian) PHP/5.2.6-2+b1 with Suhosin-Patch mod_ssl/2.2.6 OpenSSL/0.9.8g");
1659 sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
1660 sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
1661 sw.WriteLine ("Connection: close");
1665 return Encoding.UTF8.GetBytes (sw.ToString ());
1668 static byte [] VerbEchoHandler (Socket socket)
1670 MemoryStream ms = new MemoryStream ();
1671 byte [] buffer = new byte [4096];
1672 int bytesReceived = socket.Receive (buffer);
1673 while (bytesReceived > 0) {
1674 ms.Write (buffer, 0, bytesReceived);
1675 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1676 // after sending the headers
1678 if (socket.Available > 0) {
1679 bytesReceived = socket.Receive (buffer);
1686 string statusLine = null;
1687 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1688 statusLine = sr.ReadLine ();
1691 string verb = "DEFAULT";
1692 if (statusLine != null) {
1693 string [] parts = statusLine.Split (' ');
1694 if (parts.Length > 0)
1698 StringWriter sw = new StringWriter ();
1699 sw.WriteLine ("HTTP/1.1 200 OK");
1700 sw.WriteLine ("Content-Type: text/plain");
1701 sw.WriteLine ("Content-Length: " + verb.Length);
1706 return Encoding.UTF8.GetBytes (sw.ToString ());
1709 static byte [] PostAnd401Handler (Socket socket)
1711 MemoryStream ms = new MemoryStream ();
1712 byte [] buffer = new byte [4096];
1713 int bytesReceived = socket.Receive (buffer);
1714 while (bytesReceived > 0) {
1715 ms.Write (buffer, 0, bytesReceived);
1716 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1717 // after sending the headers
1719 if (socket.Available > 0) {
1720 bytesReceived = socket.Receive (buffer);
1727 string statusLine = null;
1728 bool have_auth = false;
1730 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1732 while ((l = sr.ReadLine ()) != null) {
1733 if (statusLine == null) {
1735 } else if (l.StartsWith ("Authorization:")) {
1737 } else if (l.StartsWith ("Content-Length:")) {
1738 cl = Int32.Parse (l.Substring ("content-length: ".Length));
1743 StringWriter sw = new StringWriter ();
1745 sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
1746 sw.WriteLine ("WWW-Authenticate: basic Yeah");
1749 } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
1750 sw.WriteLine ("HTTP/1.0 200 OK");
1751 sw.WriteLine ("Content-Type: text/plain");
1752 sw.WriteLine ("Content-Length: 8");
1754 sw.Write ("LOOKS OK");
1757 sw.WriteLine ("HTTP/1.0 500 test failed");
1758 sw.WriteLine ("Content-Length: 0");
1763 return Encoding.UTF8.GetBytes (sw.ToString ());
1766 public void NtlmAuthentication ()
1768 NtlmServer server = new NtlmServer ();
1771 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
1772 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
1773 request.Timeout = 5000;
1774 request.Credentials = new NetworkCredential ("user", "password", "domain");
1775 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
1777 using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
1778 res = reader.ReadToEnd ();
1782 Assert.AreEqual ("OK", res);
1785 class NtlmServer : HttpServer {
1786 public string Where = "";
1787 protected override void Run ()
1789 Where = "before accept";
1790 Socket client = sock.Accept ();
1791 NetworkStream ns = new NetworkStream (client, false);
1792 StreamReader reader = new StreamReader (ns, Encoding.ASCII);
1794 Where = "first read";
1795 while ((line = reader.ReadLine ()) != null) {
1796 if (line.Trim () == String.Empty) {
1800 Where = "first write";
1801 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1802 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1803 "WWW-Authenticate: NTLM\r\n" +
1804 "Content-Length: 5\r\n\r\nWRONG");
1807 Where = "second read";
1808 while ((line = reader.ReadLine ()) != null) {
1809 if (line.Trim () == String.Empty) {
1813 Where = "second write";
1814 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1815 "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
1816 "Content-Length: 5\r\n\r\nWRONG");
1819 Where = "third read";
1820 while ((line = reader.ReadLine ()) != null) {
1821 if (line.Trim () == String.Empty) {
1825 Where = "third write";
1826 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1827 "Keep-Alive: true\r\n" +
1828 "Content-Length: 2\r\n\r\nOK");
1830 Thread.Sleep (1000);
1837 class BadChunkedServer : HttpServer {
1838 protected override void Run ()
1840 Socket client = sock.Accept ();
1841 NetworkStream ns = new NetworkStream (client, true);
1842 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1843 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1844 "Transfer-Encoding: chunked\r\n" +
1845 "Connection: close\r\n" +
1846 "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
1848 // This body lacks a 'last-chunk' (see RFC 2616)
1849 writer.Write ("10\r\n1234567890123456\r\n");
1851 client.Shutdown (SocketShutdown.Send);
1852 Thread.Sleep (1000);
1857 class AcceptAllPolicy : ICertificatePolicy {
1858 public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
1864 abstract class HttpServer
1866 protected Socket sock;
1867 protected Exception error;
1868 protected ManualResetEvent evt;
1870 public HttpServer ()
1872 sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
1873 sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
1877 public void Start ()
1879 evt = new ManualResetEvent (false);
1880 Thread th = new Thread (new ThreadStart (Run));
1890 public IPAddress IPAddress {
1891 get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
1895 get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
1898 public Exception Error {
1899 get { return error; }
1902 protected abstract void Run ();
1906 public void BeginGetRequestStream ()
1912 r.ContentLength = 0;
1913 r.BeginGetRequestStream ((a) =>
1915 using (Stream s = r.EndGetRequestStream (a)) { };
1924 public void BeginGetRequestStreamNoClose ()
1929 r.ContentLength = 1;
1930 r.BeginGetRequestStream ((a) =>
1932 r.EndGetRequestStream (a);
1941 public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
1947 r.ContentLength = 10;
1948 r.BeginGetRequestStream ((a) =>
1950 WebException ex = ExceptionAssert.Throws<WebException> (() =>
1952 using (Stream s = r.EndGetRequestStream (a)) {
1956 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1965 public void GetRequestStream2 ()
1971 r.ContentLength = data64KB.Length;
1972 using (Stream s = r.GetRequestStream ()) {
1973 s.Write (data64KB, 0, data64KB.Length);
1981 public void GetRequestStreamNotAllBytesWritten ()
1987 r.ContentLength = data64KB.Length;
1988 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
1989 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1996 public void GetRequestStreamTimeout ()
2002 r.ContentLength = data64KB.Length;
2004 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
2005 Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
2011 public void BeginWrite ()
2013 byte[] received = new byte[data64KB.Length];
2019 r.ContentLength = data64KB.Length;
2021 Stream s = r.GetRequestStream ();
2022 s.BeginWrite (data64KB, 0, data64KB.Length,
2027 r.GetResponse ().Close ();
2034 c.Request.InputStream.ReadAll (received, 0, received.Length);
2035 c.Response.StatusCode = 204;
2036 c.Response.Close ();
2039 Assert.AreEqual (data64KB, received);
2043 public void BeginWriteAfterAbort ()
2045 byte [] received = new byte [data64KB.Length];
2051 r.ContentLength = data64KB.Length;
2053 Stream s = r.GetRequestStream ();
2056 WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
2057 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2063 //c.Request.InputStream.ReadAll (received, 0, received.Length);
2064 //c.Response.StatusCode = 204;
2065 //c.Response.Close();
2070 public void PrematureStreamCloseAborts ()
2072 byte [] received = new byte [data64KB.Length];
2078 r.ContentLength = data64KB.Length * 2;
2080 Stream s = r.GetRequestStream ();
2081 s.Write (data64KB, 0, data64KB.Length);
2083 WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
2084 Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
2090 c.Request.InputStream.ReadAll (received, 0, received.Length);
2091 // c.Response.StatusCode = 204;
2092 // c.Response.Close ();
2097 public void Write ()
2099 byte [] received = new byte [data64KB.Length];
2105 r.ContentLength = data64KB.Length;
2107 using (Stream s = r.GetRequestStream ()) {
2108 s.Write (data64KB, 0, data64KB.Length);
2111 r.GetResponse ().Close ();
2116 c.Request.InputStream.ReadAll (received, 0, received.Length);
2117 c.Response.StatusCode = 204;
2118 c.Response.Close ();
2121 Assert.AreEqual(data64KB, received);
2125 Invalid test: it does not work on linux.
2126 [pid 30973] send(9, "POST / HTTP/1.1\r\nContent-Length:"..., 89, 0) = 89
2128 [pid 30970] send(16, "HTTP/1.1 200 OK\r\nServer: Mono-HT"..., 133, 0) = 133
2130 [pid 30970] close(16) = 0
2132 [pid 30980] send(9, "\213t\326\350\312u\36n\234\351\225L\r\243a\200\226\371\350F\271~oZ\32\270\24\226z4\211\345"..., 65536, 0) = 65536
2134 [pid 30966] close(4) = 0
2137 The server sideis closed (FD 16) and the send on the client side (FD 9) succeeds.
2139 [Category("NotWorking")]
2140 public void WriteServerAborts ()
2142 ManualResetEvent abort = new ManualResetEvent (false);
2143 byte [] received = new byte [data64KB.Length];
2149 r.ContentLength = data64KB.Length;
2151 using (Stream s = r.GetRequestStream()) {
2154 IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
2170 byte [] received = new byte [data64KB.Length];
2175 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2176 using (Stream s = x.GetResponseStream()) {
2177 s.ReadAll (received, 0, received.Length);
2184 c.Response.StatusCode = 200;
2185 c.Response.ContentLength64 = data64KB.Length;
2186 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2187 c.Response.OutputStream.Close ();
2188 c.Response.Close ();
2191 Assert.AreEqual (data64KB, received);
2195 public void ReadTimeout2 ()
2197 byte [] received = new byte [data64KB.Length];
2202 r.ReadWriteTimeout = 10;
2203 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2204 using (Stream s = x.GetResponseStream ()) {
2205 WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
2206 Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
2213 c.Response.StatusCode = 200;
2214 c.Response.ContentLength64 = data64KB.Length;
2215 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
2216 Thread.Sleep (1000);
2217 // c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
2218 c.Response.OutputStream.Close ();
2219 c.Response.Close ();
2224 public void ReadServerAborted ()
2226 byte [] received = new byte [data64KB.Length];
2231 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2232 using (Stream s = x.GetResponseStream ()) {
2233 Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
2240 c.Response.StatusCode = 200;
2241 c.Response.ContentLength64 = data64KB.Length;
2242 c.Response.OutputStream.Write (data64KB, 0, 1);
2243 c.Response.Abort ();
2248 public void BeginGetResponse2 ()
2250 byte [] received = new byte [data64KB.Length];
2255 r.BeginGetResponse ((a) =>
2257 using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
2258 using (Stream s = x.GetResponseStream ()) {
2259 s.ReadAll (received, 0, received.Length);
2267 c.Response.StatusCode = 200;
2268 c.Response.ContentLength64 = data64KB.Length;
2269 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2270 c.Response.OutputStream.Close ();
2271 c.Response.Close ();
2274 Assert.AreEqual (data64KB, received);
2278 public void BeginGetResponseAborts ()
2280 ManualResetEvent aborted = new ManualResetEvent(false);
2285 r.BeginGetResponse((a) =>
2287 WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
2288 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2298 // Thread.Sleep (100);
2299 // c.Response.StatusCode = 200;
2300 // c.Response.ContentLength64 = 0;
2301 // c.Response.Close ();
2308 public void TestLargeDataReading ()
2310 int near2GBStartPosition = rand.Next (int.MaxValue - 500, int.MaxValue);
2311 AutoResetEvent readyGetLastPortionEvent = new AutoResetEvent (false);
2312 Exception testException = null;
2315 (request, waitHandle) =>
2319 const int timeoutMs = 5000;
2321 request.Timeout = timeoutMs;
2322 request.ReadWriteTimeout = timeoutMs;
2324 WebResponse webResponse = request.GetResponse ();
2325 Stream webResponseStream = webResponse.GetResponseStream ();
2326 Assert.IsNotNull (webResponseStream, null, "#1");
2328 Type webConnectionStreamType = webResponseStream.GetType ();
2329 FieldInfo totalReadField = webConnectionStreamType.GetField ("totalRead", BindingFlags.NonPublic | BindingFlags.Instance);
2330 Assert.IsNotNull (totalReadField, "#2");
2331 totalReadField.SetValue (webResponseStream, near2GBStartPosition);
2333 byte[] readBuffer = new byte[int.MaxValue - near2GBStartPosition];
2334 Assert.AreEqual (webResponseStream.Read (readBuffer, 0, readBuffer.Length), readBuffer.Length, "#3");
2335 readyGetLastPortionEvent.Set ();
2336 Assert.Greater (webResponseStream.Read (readBuffer, 0, readBuffer.Length), 0, "#4");
2337 readyGetLastPortionEvent.Set ();
2339 webResponse.Close();
2352 processor.Request.InputStream.Close ();
2354 HttpListenerResponse response = processor.Response;
2355 response.SendChunked = true;
2357 Stream outputStream = response.OutputStream;
2358 var writeBuffer = new byte[int.MaxValue - near2GBStartPosition];
2359 outputStream.Write (writeBuffer, 0, writeBuffer.Length);
2360 readyGetLastPortionEvent.WaitOne ();
2361 outputStream.Write (writeBuffer, 0, writeBuffer.Length);
2362 readyGetLastPortionEvent.WaitOne ();
2367 if (testException != null)
2368 throw testException;
2371 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
2373 int port = NetworkHelpers.FindFreePort ();
2375 ManualResetEvent completed = new ManualResetEvent (false);
2376 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2377 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2379 request (client, completed);
2381 if (!completed.WaitOne (10000))
2382 Assert.Fail ("Test hung");
2385 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
2387 int port = NetworkHelpers.FindFreePort ();
2389 ManualResetEvent [] completed = new ManualResetEvent [2];
2390 completed [0] = new ManualResetEvent (false);
2391 completed [1] = new ManualResetEvent (false);
2393 using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
2394 ManualResetEvent clientCompleted = new ManualResetEvent (false);
2395 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2396 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2398 ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
2400 if (!WaitHandle.WaitAll (completed, 10000))
2401 Assert.Fail ("Test hung.");
2406 [ExpectedException (typeof (ArgumentNullException))]
2407 public void NullHost ()
2409 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2414 public void NoHost ()
2416 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2417 Assert.AreEqual (req.Host, "go-mono.com");
2421 [ExpectedException (typeof (ArgumentException))]
2422 public void EmptyHost ()
2424 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2429 public void HostAndPort ()
2431 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
2432 Assert.AreEqual ("go-mono.com", req.Host, "#01");
2433 req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
2434 Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
2438 public void PortRange ()
2440 for (int i = 0; i < 65536; i++) {
2443 string s = i.ToString ();
2444 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
2445 Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
2450 [ExpectedException (typeof (ArgumentException))]
2451 public void PortBelow ()
2453 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2454 req.Host = "go-mono.com:-1";
2458 [ExpectedException (typeof (ArgumentException))]
2459 public void PortAbove ()
2461 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2462 req.Host = "go-mono.com:65536";
2466 [ExpectedException (typeof (ArgumentException))]
2467 public void HostTooLong ()
2469 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2470 string s = new string ('a', 100);
2471 req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
2475 [Category ("NotWorking")] // #5490
2476 public void InvalidNamesThatWork ()
2478 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2482 req.Host = new string ('a', 64); // Should fail. Max. is 63.
2486 public void NoDate ()
2488 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2489 Assert.AreEqual (DateTime.MinValue, req.Date);
2493 public void UtcDate ()
2495 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2496 req.Date = DateTime.UtcNow;
2497 DateTime date = req.Date;
2498 Assert.AreEqual (DateTimeKind.Local, date.Kind);
2502 public void AddAndRemoveDate ()
2504 // Neil Armstrong set his foot on Moon
2505 var landing = new DateTime (1969, 7, 21, 2, 56, 0, DateTimeKind.Utc);
2506 Assert.AreEqual (621214377600000000, landing.Ticks);
2507 var unspecified = new DateTime (1969, 7, 21, 2, 56, 0);
2508 var local = landing.ToLocalTime ();
2510 var req = (HttpWebRequest)WebRequest.Create ("http://www.mono-project.com/");
2512 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2513 Assert.AreEqual (local.Ticks, req.Date.Ticks);
2514 Assert.AreEqual (local, req.Date);
2516 req.Date = unspecified;
2517 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2518 Assert.AreEqual (unspecified.Ticks, req.Date.Ticks);
2519 Assert.AreEqual (unspecified, req.Date);
2522 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2523 Assert.AreEqual (local.Ticks, req.Date.Ticks);
2524 Assert.AreEqual (local, req.Date);
2526 req.Date = DateTime.MinValue;
2527 Assert.AreEqual (DateTimeKind.Unspecified, DateTime.MinValue.Kind);
2528 Assert.AreEqual (DateTimeKind.Unspecified, req.Date.Kind);
2529 Assert.AreEqual (0, req.Date.Ticks);
2531 Assert.AreEqual (null, req.Headers.Get ("Date"));
2536 public void TestIPv6Host ()
2538 var address = "2001:0000:0000:0001:0001:0001:0157:0000";
2539 var address2 = '[' + address + ']';
2540 var uri = new Uri (string.Format ("http://{0}/test.css", address2));
2541 var hwr = (HttpWebRequest)WebRequest.Create (uri);
2543 hwr.Host = address2;
2544 Assert.AreEqual (address2, hwr.Host, "#1");
2549 [Category ("NotWorking")]
2550 public void TestIPv6Host2 ()
2552 var address = "2001:0000:0000:0001:0001:0001:0157:0000";
2553 var address2 = '[' + address + ']';
2554 var uri = new Uri (string.Format ("http://{0}/test.css", address2));
2555 var hwr = (HttpWebRequest)WebRequest.Create (uri);
2560 } catch (ArgumentException) {
2567 public void AllowReadStreamBuffering ()
2569 var hr = WebRequest.CreateHttp ("http://www.google.com");
2570 Assert.IsFalse (hr.AllowReadStreamBuffering, "#1");
2572 hr.AllowReadStreamBuffering = true;
2574 } catch (InvalidOperationException) {
2579 class ListenerScope : IDisposable {
2580 EventWaitHandle completed;
2581 public HttpListener listener;
2582 Action<HttpListenerContext> processor;
2584 public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
2586 this.processor = processor;
2587 this.completed = completed;
2589 this.listener = new HttpListener ();
2590 this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
2591 this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
2592 this.listener.Start ();
2594 this.listener.BeginGetContext (this.RequestHandler, null);
2597 void RequestHandler (IAsyncResult result)
2599 HttpListenerContext context = null;
2602 context = this.listener.EndGetContext (result);
2603 } catch (HttpListenerException ex) {
2604 // check if the thread has been aborted as in the case when we are shutting down.
2605 if (ex.ErrorCode == 995)
2607 } catch (ObjectDisposedException) {
2611 ThreadPool.QueueUserWorkItem ((o) =>
2614 this.processor (context);
2615 } catch (HttpListenerException) {
2619 this.completed.Set ();
2622 public void Dispose ()
2624 this.listener.Stop ();
2629 class SslHttpServer : HttpServer {
2630 X509Certificate _certificate;
2632 protected override void Run ()
2635 Socket client = sock.Accept ();
2636 NetworkStream ns = new NetworkStream (client, true);
2637 SslServerStream s = new SslServerStream (ns, Certificate, false, false);
2638 s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
2640 StreamReader reader = new StreamReader (s);
2641 StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
2644 string hello = "<html><body><h1>Hello World!</h1></body></html>";
2645 string answer = "HTTP/1.0 200\r\n" +
2646 "Connection: close\r\n" +
2647 "Content-Type: text/html\r\n" +
2648 "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
2649 "Content-Length: " + hello.Length + "\r\n" +
2654 line = reader.ReadLine ();
2655 } while (line != "" && line != null && line.Length > 0);
2657 // Now the content. We know it's 100 bytes.
2658 // This makes BeginRead in sslclientstream block.
2659 char [] cs = new char [100];
2660 reader.Read (cs, 0, 100);
2662 writer.Write (answer);
2664 if (evt.WaitOne (5000, false))
2665 error = new Exception ("Timeout when stopping the server");
2666 } catch (Exception e) {
2671 X509Certificate Certificate {
2673 if (_certificate == null)
2674 _certificate = new X509Certificate (CertData.Certificate);
2676 return _certificate;
2680 AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
2682 PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
2688 public readonly static byte [] Certificate = {
2689 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
2690 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
2691 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
2692 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
2693 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
2694 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
2695 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
2696 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
2697 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
2698 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
2699 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
2700 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
2701 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
2702 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
2703 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
2704 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
2705 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
2706 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
2707 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
2708 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
2709 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
2710 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
2711 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
2712 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
2713 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
2714 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
2715 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
2716 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
2720 public readonly static byte [] PrivateKey = {
2721 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
2722 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
2723 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
2724 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
2725 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
2726 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
2727 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
2728 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
2729 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
2730 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
2731 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
2732 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
2733 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
2734 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
2735 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
2736 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
2737 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
2738 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
2739 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
2740 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
2741 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
2742 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
2743 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
2744 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
2745 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
2746 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
2747 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
2748 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
2749 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
2750 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
2751 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
2752 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
2753 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
2754 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
2755 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
2756 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
2757 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
2758 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
2759 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
2765 public void CookieContainerTest ()
2767 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2768 string url = "http://" + ep.ToString ();
2770 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (CookieRequestHandler))) {
2773 CookieContainer container = new CookieContainer ();
2774 container.Add(new Uri (url), new Cookie ("foo", "bar"));
2775 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
2776 request.CookieContainer = container;
2777 WebHeaderCollection headers = request.Headers;
2778 headers.Add("Cookie", "foo=baz");
2779 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
2780 string responseString = null;
2781 using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
2782 responseString = reader.ReadToEnd ();
2785 Assert.AreEqual (1, response.Cookies.Count, "#01");
2786 Assert.AreEqual ("foo=bar", response.Headers.Get("Set-Cookie"), "#02");
2789 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (CookieRequestHandler))) {
2792 CookieContainer container = new CookieContainer ();
2793 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
2794 request.CookieContainer = container;
2795 WebHeaderCollection headers = request.Headers;
2796 headers.Add("Cookie", "foo=baz");
2797 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
2798 string responseString = null;
2799 using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
2800 responseString = reader.ReadToEnd ();
2803 Assert.AreEqual (0, response.Cookies.Count, "#03");
2804 Assert.AreEqual ("", response.Headers.Get("Set-Cookie"), "#04");
2808 internal static byte[] CookieRequestHandler (Socket socket)
2810 MemoryStream ms = new MemoryStream ();
2811 byte[] buffer = new byte[4096];
2812 int bytesReceived = socket.Receive (buffer);
2813 while (bytesReceived > 0) {
2814 ms.Write(buffer, 0, bytesReceived);
2815 // We don't check for Content-Length or anything else here, so we give the client a little time to write
2816 // after sending the headers
2818 if (socket.Available > 0) {
2819 bytesReceived = socket.Receive (buffer);
2826 string cookies = string.Empty;
2827 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
2829 while ((line = sr.ReadLine ()) != null) {
2830 if (line.StartsWith ("Cookie:")) {
2831 cookies = line.Substring ("cookie: ".Length);
2836 StringWriter sw = new StringWriter ();
2837 sw.WriteLine ("HTTP/1.1 200 OK");
2838 sw.WriteLine ("Content-Type: text/xml");
2839 sw.WriteLine ("Set-Cookie: " + cookies);
2840 sw.WriteLine ("Content-Length: " + cookies.Length.ToString (CultureInfo.InvariantCulture));
2845 return Encoding.UTF8.GetBytes (sw.ToString ());
2850 public class HttpRequestStreamTest
2853 public void BeginRead ()
2855 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2856 string url = "http://" + ep.ToString () + "/test/";
2858 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2861 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2862 req.Method = "POST";
2864 using (Stream rs = req.GetRequestStream ()) {
2865 byte [] buffer = new byte [10];
2867 rs.BeginRead (buffer, 0, buffer.Length, null, null);
2869 } catch (NotSupportedException ex) {
2870 // The stream does not support reading
2871 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2872 Assert.IsNull (ex.InnerException, "#3");
2873 Assert.IsNotNull (ex.Message, "#4");
2882 [Category("MobileNotWorking")]
2883 public void BeginWrite_Request_Aborted ()
2885 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2886 string url = "http://" + ep.ToString () + "/test/";
2888 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2891 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2892 req.Method = "POST";
2894 using (Stream rs = req.GetRequestStream ()) {
2897 rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
2899 } catch (WebException ex) {
2900 // The request was aborted: The request was canceled
2901 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2902 Assert.IsNull (ex.InnerException, "#3");
2903 Assert.IsNotNull (ex.Message, "#4");
2904 Assert.IsNull (ex.Response, "#5");
2905 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2912 public void CanRead ()
2914 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2915 string url = "http://" + ep.ToString () + "/test/";
2917 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2920 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2921 req.Method = "POST";
2923 Stream rs = req.GetRequestStream ();
2925 Assert.IsFalse (rs.CanRead, "#1");
2927 Assert.IsFalse (rs.CanRead, "#2");
2936 public void CanSeek ()
2938 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2939 string url = "http://" + ep.ToString () + "/test/";
2941 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2944 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2945 req.Method = "POST";
2947 Stream rs = req.GetRequestStream ();
2949 Assert.IsFalse (rs.CanSeek, "#1");
2951 Assert.IsFalse (rs.CanSeek, "#2");
2959 [Test] // bug #324182
2960 public void CanTimeout ()
2962 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2963 string url = "http://" + ep.ToString () + "/test/";
2965 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2968 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2969 req.Method = "POST";
2971 Stream rs = req.GetRequestStream ();
2973 Assert.IsTrue (rs.CanTimeout, "#1");
2975 Assert.IsTrue (rs.CanTimeout, "#2");
2984 public void CanWrite ()
2986 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2987 string url = "http://" + ep.ToString () + "/test/";
2989 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2992 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2993 req.Method = "POST";
2995 Stream rs = req.GetRequestStream ();
2997 Assert.IsTrue (rs.CanWrite, "#1");
2999 Assert.IsFalse (rs.CanWrite, "#2");
3010 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3011 string url = "http://" + ep.ToString () + "/test/";
3013 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3016 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3017 req.Method = "POST";
3019 using (Stream rs = req.GetRequestStream ()) {
3020 byte [] buffer = new byte [10];
3022 rs.Read (buffer, 0, buffer.Length);
3024 } catch (NotSupportedException ex) {
3025 // The stream does not support reading
3026 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
3027 Assert.IsNull (ex.InnerException, "#3");
3028 Assert.IsNotNull (ex.Message, "#4");
3037 public void ReadByte ()
3039 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3040 string url = "http://" + ep.ToString () + "/test/";
3042 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3045 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3046 req.Method = "POST";
3048 using (Stream rs = req.GetRequestStream ()) {
3052 } catch (NotSupportedException ex) {
3053 // The stream does not support reading
3054 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
3055 Assert.IsNull (ex.InnerException, "#3");
3056 Assert.IsNotNull (ex.Message, "#4");
3065 public void ReadTimeout ()
3067 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3068 string url = "http://" + ep.ToString () + "/test/";
3070 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3073 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3074 req.Method = "POST";
3076 Stream rs = req.GetRequestStream ();
3078 Assert.AreEqual (300000, rs.ReadTimeout, "#1");
3080 Assert.AreEqual (300000, rs.ReadTimeout, "#2");
3091 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3092 string url = "http://" + ep.ToString () + "/test/";
3094 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3097 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3098 req.Method = "POST";
3100 using (Stream rs = req.GetRequestStream ()) {
3102 rs.Seek (0, SeekOrigin.Current);
3104 } catch (NotSupportedException ex) {
3105 // This stream does not support seek operations
3106 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
3107 Assert.IsNull (ex.InnerException, "#3");
3108 Assert.IsNotNull (ex.Message, "#4");
3117 public void Write_Buffer_Null ()
3119 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3120 string url = "http://" + ep.ToString () + "/test/";
3122 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3125 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3126 req.Method = "POST";
3128 using (Stream rs = req.GetRequestStream ()) {
3130 rs.Write ((byte []) null, -1, -1);
3132 } catch (ArgumentNullException ex) {
3133 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3134 Assert.IsNull (ex.InnerException, "#3");
3135 Assert.IsNotNull (ex.Message, "#4");
3136 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3145 public void Write_Count_Negative ()
3147 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3148 string url = "http://" + ep.ToString () + "/test/";
3150 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3153 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3154 req.Method = "POST";
3156 using (Stream rs = req.GetRequestStream ()) {
3157 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3159 rs.Write (buffer, 1, -1);
3161 } catch (ArgumentOutOfRangeException ex) {
3162 // Specified argument was out of the range of valid values
3163 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3164 Assert.IsNull (ex.InnerException, "#A3");
3165 Assert.IsNotNull (ex.Message, "#A4");
3166 Assert.AreEqual ("size", ex.ParamName, "#A5");
3175 public void Write_Count_Overflow ()
3177 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3178 string url = "http://" + ep.ToString () + "/test/";
3180 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3183 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3184 req.Method = "POST";
3186 using (Stream rs = req.GetRequestStream ()) {
3187 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3189 rs.Write (buffer, buffer.Length - 2, 3);
3191 } catch (ArgumentOutOfRangeException ex) {
3192 // Specified argument was out of the range of valid values
3193 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3194 Assert.IsNull (ex.InnerException, "#3");
3195 Assert.IsNotNull (ex.Message, "#4");
3196 Assert.AreEqual ("size", ex.ParamName, "#5");
3205 public void Write_Offset_Negative ()
3207 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3208 string url = "http://" + ep.ToString () + "/test/";
3210 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3213 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3214 req.Method = "POST";
3216 using (Stream rs = req.GetRequestStream ()) {
3217 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3219 rs.Write (buffer, -1, 0);
3221 } catch (ArgumentOutOfRangeException ex) {
3222 // Specified argument was out of the range of valid values
3223 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3224 Assert.IsNull (ex.InnerException, "#3");
3225 Assert.IsNotNull (ex.Message, "#4");
3226 Assert.AreEqual ("offset", ex.ParamName, "#5");
3235 public void Write_Offset_Overflow ()
3237 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3238 string url = "http://" + ep.ToString () + "/test/";
3240 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3243 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3244 req.Method = "POST";
3246 using (Stream rs = req.GetRequestStream ()) {
3247 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3249 rs.Write (buffer, buffer.Length + 1, 0);
3251 } catch (ArgumentOutOfRangeException ex) {
3252 // Specified argument was out of the range of valid values
3253 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3254 Assert.IsNull (ex.InnerException, "#3");
3255 Assert.IsNotNull (ex.Message, "#4");
3256 Assert.AreEqual ("offset", ex.ParamName, "#5");
3265 public void Write_Request_Aborted ()
3267 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3268 string url = "http://" + ep.ToString () + "/test/";
3270 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3273 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3274 req.Method = "POST";
3276 using (Stream rs = req.GetRequestStream ()) {
3279 rs.Write (new byte [0], 0, 0);
3281 } catch (WebException ex) {
3282 // The request was aborted: The request was canceled
3283 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3284 Assert.IsNull (ex.InnerException, "#3");
3285 Assert.IsNotNull (ex.Message, "#4");
3286 Assert.IsNull (ex.Response, "#5");
3287 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3294 [Category ("NotWorking")]
3295 public void Write_Stream_Closed ()
3297 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3298 string url = "http://" + ep.ToString () + "/test/";
3300 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3303 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3304 req.Method = "POST";
3306 using (Stream rs = req.GetRequestStream ()) {
3309 rs.Write (new byte [0], 0, 0);
3311 } catch (WebException ex) {
3312 // The request was aborted: The connection was closed unexpectedly
3313 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3314 Assert.IsNull (ex.InnerException, "#3");
3315 Assert.IsNotNull (ex.Message, "#4");
3316 Assert.IsNull (ex.Response, "#5");
3317 Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
3324 public void WriteByte_Request_Aborted ()
3326 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3327 string url = "http://" + ep.ToString () + "/test/";
3329 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3332 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3333 req.Method = "POST";
3335 using (Stream rs = req.GetRequestStream ()) {
3338 rs.WriteByte (0x2a);
3340 } catch (WebException ex) {
3341 // The request was aborted: The request was canceled
3342 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3343 Assert.IsNull (ex.InnerException, "#3");
3344 Assert.IsNotNull (ex.Message, "#4");
3345 Assert.IsNull (ex.Response, "#5");
3346 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3353 public void WriteTimeout ()
3355 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3356 string url = "http://" + ep.ToString () + "/test/";
3358 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3361 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3362 req.Method = "POST";
3364 Stream rs = req.GetRequestStream ();
3366 Assert.AreEqual (300000, rs.WriteTimeout, "#1");
3368 Assert.AreEqual (300000, rs.WriteTimeout, "#2");
3378 // This test is supposed to fail prior to .NET 4.0
3379 public void Post_EmptyRequestStream ()
3381 var wr = HttpWebRequest.Create ("http://google.com");
3383 wr.GetRequestStream ();
3385 var gr = wr.BeginGetResponse (delegate { }, null);
3386 Assert.AreEqual (true, gr.AsyncWaitHandle.WaitOne (5000), "#1");
3390 static class StreamExtensions {
3391 public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
3395 while (totalRead < count) {
3396 int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
3400 totalRead += bytesRead;
3407 static class ExceptionAssert {
3409 /// Asserts that the function throws an exception.
3411 /// <param name="f">A function execute that is expected to raise an exception.</param>
3412 /// <typeparam name="T">The type of exception that is expected.</typeparam>
3413 /// <returns>The exception thrown.</returns>
3414 /// <exception cref="AssertFailedException">If the function does not throw an exception
3415 /// or throws a different exception.</exception>
3416 /// <example><![CDATA[
3417 /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
3418 /// myObject.myFunction(null); });
3420 public static T Throws<T> (Action f) where T : Exception {
3421 Exception actualException = null;
3425 } catch (Exception ex) {
3426 actualException = ex;
3429 if (actualException == null)
3430 throw new AssertionException (string.Format (
3431 "No exception thrown. Expected '{0}'",
3432 typeof (T).FullName));
3433 else if (typeof(T) != actualException.GetType())
3434 throw new AssertionException (string.Format (
3435 "Caught exception of type '{0}'. Expected '{1}':{2}",
3436 actualException.GetType().FullName,
3437 typeof (T).FullName,
3438 Environment.NewLine + actualException));
3440 return (T) actualException;