Permalink
Browse files

New extension methods for HTTP requests

Added new extension methods to simplify creating/reading HTTP Web
Requests.
  • Loading branch information...
1 parent 97ba91a commit 66c3fc582a59a50d08f83105a1d085fb76e6433c @jarrettmeyer jarrettmeyer committed Jan 30, 2012
@@ -64,6 +64,7 @@
<Compile Include="Math\EpsilonExtensionsTests.cs" />
<Compile Include="Math\LinearSystemTests.cs" />
<Compile Include="Messaging\BusTests.cs" />
+ <Compile Include="Net\NetExtesionsTests.cs" />
<Compile Include="ObjectExtensionsTests.cs" />
<Compile Include="PluralizationTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
@@ -86,6 +87,7 @@
<Name>Curiosity.Common</Name>
</ProjectReference>
</ItemGroup>
+ <ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -0,0 +1,67 @@
+using System;
+using System.IO;
+using System.Net;
+using NUnit.Framework;
+
+namespace Curiosity.Common.Net
+{
+ [TestFixture]
+ public class NetExtesionsTests
+ {
+ public class ReadResponseStringToBytes_Method
+ {
+ [Test]
+ public void can_get_response_content_as_bytes()
+ {
+ var response = "http://curiositysoftware.com".ToHttpResponse();
+ var content = response.ReadResponseStreamToBytes();
+ Assert.Greater(content.Length, 0);
+ }
+ }
+
+ public class ReadResponseStreamToString_Method
+ {
+ [Test]
+ public void can_get_response_content_as_string()
+ {
+ var response = "http://curiositysoftware.com".ToHttpResponse();
+ var content = response.ReadResponseStreamToString();
+ Assert.Greater(content.Length, 0);
+ StringAssert.Contains("<!DOCTYPE html>", content);
+ }
+ }
+
+ public class ToHttpRequest_Method
+ {
+ [Test]
+ public void can_create_http_request()
+ {
+ var request = "http://google.com".ToHttpRequest();
+ Assert.IsNotNull(request);
+ Assert.AreEqual(new Uri("http://google.com"), request.RequestUri);
+ }
+ }
+
+ public class ToHttpResponse_Method
+ {
+ [Test]
+ public void can_get_a_response()
+ {
+ var response = "http://google.com".ToHttpResponse();
+ Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
+ }
+ }
+
+ public class WriteRequestStream_Method
+ {
+ [Test]
+ public void can_write_request_stream()
+ {
+ var request = "http://google.com".ToHttpRequest();
+ request.Method = "POST"; // required to not be a GET request
+ request.WriteRequestStream(new byte[] { 0x00, 0x00, 0x00, 0x00 });
+ Assert.AreEqual(4, request.ContentLength);
+ }
+ }
+ }
+}
@@ -7,6 +7,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Curiosity.Common.Tests", "C
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B14EABB9-95A0-4FC5-AAB7-253F91C588C6}"
ProjectSection(SolutionItems) = preProject
+ build.msbuild = build.msbuild
build_release.cmd = build_release.cmd
publish.cmd = publish.cmd
run_tests.cmd = run_tests.cmd
@@ -67,6 +67,7 @@
<Compile Include="Messaging\IQueryMessage.cs" />
<Compile Include="Messaging\MessageHandlerBase.cs" />
<Compile Include="Messaging\QueryMessageBase.cs" />
+ <Compile Include="Net\NetExtensions.cs" />
<Compile Include="ObjectExtensions.cs" />
<Compile Include="Pluralization.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
@@ -4,10 +4,10 @@
<id>Curiosity.Common</id>
<version>$version$</version>
<authors>Jarrett Meyer</authors>
- <owners>Jarrett Meyer</owners>
+ <owners>Curiosity Software, LLC</owners>
<projectUrl>https://github.com/jarrettmeyer/curiosity-common</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
- <description>Common class library for Curiosity software.</description>
- <copyright>Copyright 2011</copyright>
+ <description>Common class library for Curiosity Software.</description>
+ <copyright>Copyright 2012</copyright>
</metadata>
</package>
@@ -0,0 +1,102 @@
+using System;
+using System.Net;
+using System.Text;
+
+namespace Curiosity.Common.Net
+{
+ public static class NetExtensions
+ {
+ /// <summary>
+ /// Gets the HTTP response object from the given request.
+ /// </summary>
+ public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
+ {
+ ThrowUtil.ThrowExceptionIfArgumentIsNull(request, "request");
+ var response = (HttpWebResponse)request.GetResponse();
+ return response;
+ }
+
+ public static byte[] ReadResponseStreamToBytes(this WebResponse response)
+ {
+ int contentLength;
+ if (!TryGetContentLength(response, out contentLength))
+ {
+ return new byte[] { };
+ }
+ byte[] buffer = new byte[contentLength];
+ using (var stream = response.GetResponseStream())
+ {
+ if (stream == null)
+ {
+ throw new NullReferenceException("Unable to read stream from web response.");
+ }
+ stream.Read(buffer, 0, contentLength);
+ }
+ return buffer;
+ }
+
+ /// <summary>
+ /// Gets the response content as a string. The default encoding is UTF-8.
+ /// </summary>
+ /// <param name="response"></param>
+ /// <param name="encoding"></param>
+ /// <returns></returns>
+ public static string ReadResponseStreamToString(this WebResponse response, Encoding encoding = null)
+ {
+ ThrowUtil.ThrowExceptionIfArgumentIsNull(response, "response");
+ encoding = encoding ?? Encoding.UTF8;
+ var bytes = ReadResponseStreamToBytes(response);
+ var responseString = encoding.GetString(bytes);
+ return responseString;
+ }
+
+ /// <summary>
+ /// Converts a string to an HTTP request.
+ /// </summary>
+ public static HttpWebRequest ToHttpRequest(this string url)
+ {
+ var request = (HttpWebRequest)WebRequest.Create(url);
+ return request;
+ }
+
+ /// <summary>
+ /// Converts a string directly to an HTTP response. This is helpful when you simply want
+ /// to perform a GET to a given URL.
+ /// </summary>
+ public static HttpWebResponse ToHttpResponse(this string url)
+ {
+ var request = url.ToHttpRequest();
+ var response = request.GetHttpResponse();
+ return response;
+ }
+
+ public static void WriteRequestStream(this HttpWebRequest request, byte[] content)
+ {
+ int contentLength = content.Length;
+ request.ContentLength = contentLength;
+ using (var stream = request.GetRequestStream())
+ {
+ stream.Write(content, 0, contentLength);
+ }
+ }
+
+ private static bool TryGetContentLength(WebResponse response, out int contentLength)
+ {
+ try
+ {
+ long contentLengthLong = response.ContentLength;
+ if (contentLengthLong > int.MaxValue)
+ {
+ throw new IndexOutOfRangeException(string.Format("Unable to get HTTP response. The content exceeds {0}. Actual Length: {1}", int.MaxValue, contentLengthLong));
+ }
+ contentLength = (int)contentLengthLong;
+ return true;
+ }
+ catch (Exception)
+ {
+ contentLength = 0;
+ return false;
+ }
+ }
+ }
+}

0 comments on commit 66c3fc5

Please sign in to comment.