Introduction
While C# offers many ways for programmers to consume services from web services with relative ease, writing asynchronously takes more effort to implement than you’d like. Windows Communication Framework is a great tool for client/server communication in new builds, I've often found myself having to write a lot of code to use existing APIs. To achieve this,
WebClient
or HttpWebRequest
are used in C#, however these libraries that Microsoft provide are often too complex for most simple uses. HttpLib makes it easier to asynchronously consume data from web services in C#. The library contains methods to upload files to server and get pages in one line statements, rather than 30 lines needed to use
HttpWebReqeust
.
This now library has Windows Store compatible source and binaries available - in detail updates and explanations on my blog http://jthorne.co.uk/blog/category/httplib
HttpLib can be downloaded from the codeplex site on http://httplib.codeplex.com/.
Background
Users should be familiar with GET, POST, and similar web request types prior to using this library, however extensive knowledge is not needed.
Using the code
GET a web page
This asynchronous method asynchronously gets a web page and passes the result into a lambda expression.
Request.Get("http://codeproject.com/",
result=>
{
Console.Write(result);
});
POSTing data to web services
Data can be posted to web services in a similar manner. Parameters can be passed into an anonymous object which is later serialized into the request body.
Request.Post("http://testing.local/post.php", new {name="James",username="Redslide"},
result=>
{
Console.Write(result);
});
Uploading Files to server.
The library facilitates Multipart/form-encoded file uploads. FileStreams can be copied into the web request as shown below. The use of a stream allows the library to used in Silverlight applications for uploading an ImageStream directly from the camera.
Request.Upload("http://testing.local/post.php", new {name = "value"},
new [] {new NamedFileStream("file", "photo.jpg", "image/jpeg",
new FileStream(@"C:\photo.jpg",FileMode.Open))},
result=>
{
Console.Write(result);
});
Points of Interest
Anonymous Object Serialization
Anonymous objects are serialized using reflection. A list of all properties of an object can be obtained
using GetProperties()
. This allows the serializer to iterate through and get all the required values.
foreach (var property in Parameters.GetType().GetProperties())
{
string name = property.Name
string value = property.GetValue(Parameters, null).ToString();
}
History
- 1/5/2013 - Windows 8 info added
- 1/1/2013 - Changed type from article to tip.
- 30/12/2012 - First revision.