<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bizcoder &#187; HTTPClient</title>
	<atom:link href="http://www.bizcoder.com/index.php/tag/httpclient/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bizcoder.com</link>
	<description>Developing business applications for small businesses</description>
	<lastBuildDate>Sat, 28 Aug 2010 10:44:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Agent Fielding is on a mission</title>
		<link>http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/</link>
		<comments>http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/#comments</comments>
		<pubDate>Sat, 28 Aug 2010 10:34:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/</guid>
		<description><![CDATA[This is a continuation of a series on a Rest Agent library I am building for accessing REST apis.&#160; The first post is here and and the second is here. So far the only significant operation that we enabled our RestAgent to perform is NavigateTo().&#160; However, for a RestAgent on a mission, going places is [...]]]></description>
			<content:encoded><![CDATA[<p>This is a continuation of a series on a Rest Agent library I am building for accessing REST apis.&#160; The first post is <a href="http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/">here</a> and and the second is <a href="http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/">here</a>. </p>
<p>So far the only significant operation that we enabled our RestAgent to perform is NavigateTo().&#160; However, for a RestAgent on a mission, going places is only half the story, the other major purpose of the agent is to gather content.</p>
<p>I was planning to show some real examples of missions using Stack Overflow’s API, but I ended up spending so much time explaining why it currently would not work, that my points were lost.&#160; So forgive me as I continue with a somewhat more hypothetical example.&#160; We are going to use an instance of our RestAgent to do a mashup of Twitter users and Stackoverflow users.</p>
<div>
<pre class="csharpcode">var agentFielding = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient()); 

agentFielding.RegisterMediaType(“application/twitterdoc+xml”,
                                    <span class="kwrd">new</span> TwitterMediaHandler());
agentFielding.RegisterMediaType(“application/stackoverflowdoc+xml”,
                                    <span class="kwrd">new</span> StackOverflowMediaHandler());</pre>
</div>
<p>In the following code, Agent Fielding retrieves my Twitter followers and attempts to find matching accounts on Stack Overflow.&#160; In order to interpret the representations that will be retrieved from these two sites, we are going to pretend that these sites actually return non-generic media types and we register handlers for these media types that will transform the wire representation into strong types.</p>
<p>The first step is to navigate Twitter and retrieve the user profiles of my followers:</p>
<div>
<pre class="csharpcode">agentFielding.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.twitter.com/”));</span>
var userSearch = agentFielding.CurrentLinks(“UserSearch”);
userSearch.SetParameter(&quot;darrel_miller”);
agentFielding.NavigateTo(userSearch);

var followersLink = agentFielding.CurrentLinks[“Followers”);
agentFielding.NavigateTo(followersLink);

var twitterUserProfiles = <span class="kwrd">new</span> List&lt;TwitterUserProfile&gt;();
var followerLinks = agentFielding.GetCurrentLinks(l=&gt; l.Relation.Name == ”Follower”];
<span class="kwrd">foreach</span>(Link followerLink <span class="kwrd">in</span> followerLinks) {

  var twitterProfile = agentFielding.GetContent(followerLink).ReadAsTwitterUserProfile();
  twitterUserProfiles.Add(twitterProfile);

}</pre>
</div>
<p>Now we have a list of TwitterUserProfile objects from which we can retrieve the name and search on Stack Overflow.</p>
<div>
<pre class="csharpcode">agentFielding.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.stackoverflow.com/1.0/”));</span> 

agentFielding.NavigateTo(agent.CurrentLinks[“Users”]);
var searchLink = agent.CurrentLinks[“Search”];
var foundProfiles = <span class="kwrd">new</span> List&lt;StackOverflowUserProfile&gt;();
<span class="kwrd">foreach</span>(var profile <span class="kwrd">in</span> twitterUserProfiles) {   searchLink.SetParameter(profile.UserName);
  agentFielding.NavigateTo(searchLink); 

  var matchingUserLinks = agentFielding.GetCurrentLinks(l=&gt; l.Relation.Name == ”User”])
  <span class="kwrd">foreach</span>(Link userLink <span class="kwrd">in</span> matchingUserLinks) {
       var content = agentFielding.GetContent(userLink);
       foundProfiles.Add(content.ReadAsStackOverflowUserProfile();
  }
}</pre>
</div>
<p>Don’t get too hung up on the precise details of the above, there is a bit of smoke and mirrors going on.&#160; I’m really just trying to convey the concept that the same agent class can be used to navigate multiple different services.&#160; This brings the concept of the uniform interface a little further into the client code.&#160; </p>
<p>My hope is that in the future that REST api producers will supply media type handlers for their custom media types and we can use a standardized agent like interface for navigating any REST api.&#160; There will be no need the API producers to create complete client side facades.</p>
<p>There is still plenty of coupling in the above example, when it comes to handling specific representations and knowing about the existence of specific links, there is plenty of service specific code.&#160; This is especially true of these type of scripted or (machine to machine) interactions.&#160; Machines are really dumb, so they need to understand a lot of specifics of the services that they are interacting with.&#160; In the next article I’m going to start digging into how you can use an agent to react to a human driven application, and that will&#160; further reduce the coupling.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/08/28/agent-fielding-is-on-a-mission/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Rest Agent uses hypermedia</title>
		<link>http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/</link>
		<comments>http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 11:46:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/</guid>
		<description><![CDATA[As I alluded to in my first post, REST clients really should be driven by hypermedia.&#160; So how can our RestAgent class access this hypermedia and its links.&#160; Ideally, given a single root URI, I would like to be able to do: var agent = new RestAgent(new HttpClient()); agent.NavigateTo(new Uri(“http://api.stackoverflow.com/”)); var questionsLink = agent.CurrentLinks[“Questions”] agent.NavigateTo(questionsLink); [...]]]></description>
			<content:encoded><![CDATA[<p>As I alluded to in <a href="http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/">my first post</a>, REST clients really should be driven by hypermedia.&#160; So how can our RestAgent class access this hypermedia and its links.&#160; Ideally, given a single root URI, I would like to be able to do:</p>
<div>
<pre class="csharpcode">var agent = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient());
agent.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.stackoverflow.com/”)); </span>
var questionsLink = agent.CurrentLinks[“Questions”]
agent.NavigateTo(questionsLink);
var questions = agent.CurrentContent.ReadAsJson(); </pre>
</div>
<p>Before I talk about the magic that is going on under the covers here, let me take a little jab at my friend StackOverflow.&#160; The above code would not work, because when the team created the api, they chose not to put a root representation on the API. Making the request to the root of the api actually redirects to an html page with API documentation.&#160; I’ve tried scraping the urls out of that document, but it is proving to be painful.</p>
<h3>The Link Class</h3>
<p>The CurrentLinks property makes a dictionary of links available based on the links contained in the current content and potentially links that were included in the header.&#160; You will notice that the second call to NavigateTo passes a “Link”, not a URL.&#160; So what’s the difference?&#160; Here is a basic implementation of the Link class:</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Link {

  <span class="kwrd">public</span> <span class="kwrd">string</span> Name{ get; set;}
  <span class="kwrd">public</span> LinkRelation Relation{ get; set;}
  <span class="kwrd">public</span> Uri Url { get; set;}
  <span class="kwrd">public</span> HttpMethod Method { get; set;}
  <span class="kwrd">public</span> HttpContent Content {get; set;}

  <span class="kwrd">public</span> Dictionary&lt;Parameter&gt; QueryParameters {get; set;}
  <span class="kwrd">public</span> Dictionary&lt;Parameter&gt; PathParameters {get; set;}

}</pre>
</div>
<p>The Link class holds plenty of additional information that is needed to allow the NavigateTo method to transfer to a new state.&#160; The Link objects are created from information contained in retrieved hypermedia content.&#160; If the HttpMethod is a PUT or a POST then the Content property can be used to hold the entity that will be sent to the origin server.&#160; </p>
<p>The LinkRelation property is critical concept.&#160; The Link Relation is one of the two points of coupling between the client and the server.&#160; The other being the media-type.&#160; From an architectural point of view the Link Relation describes the relationship between two resources.&#160; For example, if you have a representation A that contains a link to resource B with the relation “edit”, this can be interpreted as B allows you to “edit” A.&#160; IANA keeps a registry of well known link relations here <a href="http://www.iana.org/assignments/link-relations/link-relations.txt">http://www.iana.org/assignments/link-relations/link-relations.txt</a>.&#160; The WHATWG group are also maintaining a list here <a href="http://wiki.whatwg.org/wiki/RelExtensions">http://wiki.whatwg.org/wiki/RelExtensions</a>.</p>
<p>From an implementation perspective, the Link Relation can be used to tell the client mechanical information about how to perform the HTTP request.&#160; For example, what HTTP method to use, what content needs to be posted back to the server, if any. It also can be used to tell the client what query string parameters are valid.&#160; Arguably you can introduce any kind of arbitrary significance to a link relation as long as you are prepared to put up with the client/server coupling.</p>
<p>I have been experimenting with implementing LinkRelation as an actual class instead of just an identifer.&#160; Many different link relations have similar sets of behaviour and by creating a base class with some standard attributes it is possible to represent specific link relations as derived classes and still have plenty of generic mechanisms that process links without scattering the code base with fragile switch statements.&#160; Hopefully as we go into more detail I will show some examples that take advantage of this LinkRelation base class.</p>
<p>So far I have only used very simple URI templates and so my needs have been satisfied with just a collection of query parameter values and path parameter values.&#160; The current draft of the URI template specification introduces many more variants that I could be supported by the Link class.</p>
<p>The Name property is the black sheep of the Link class.&#160; I’m not convinced that we really need this property.&#160; However, I include it to support the scenario where there are multiple links within a hypermedia document that has the same LinkRelation.&#160; How a client is supposed to differentiate between those different links without introducing out of band coupling is not always clear to me.&#160; If the current representation is to be rendered to the user as a set of links then the user should be capable of deciding which they wish to follow.&#160; However, in a scripted (ie. machine 2 machine) scenario, it becomes highly suspect if the script starts referring to link names.&#160; Depending on how precise the media type, is, the link names could be pre-specified in the media-type.&#160; Or code-download could be used to activate links with particular names.&#160; The final solution that I have seen is to drop the name property completely and use very specific link relation values.&#160; I’m not a big fan of this approach because I think it leads to the same explosion problems as using extremely specific media-types.&#160; Highly specific media-types and link relations destroy the possibility of serendipitous reuse.</p>
<h3>Hypermedia Content</h3>
<p>So now, you have an idea of how I handle links, let’s look at how those links get created in the first place.&#160; As I mentioned before, the CurrentLinks dictionary is populated from the CurrentContent.&#160; The question of course is how can the generic RestAgent know how to pull links out of content that could be any media type.&#160; The solution is a plug in model that allows handlers to be registered in a media type handler registry.&#160; </p>
<p>Behind the scenes I use MEF to load up the media type handlers, but I stuck an interface in front, mainly because I’m not very experienced with MEF and I wasn’t exactly sure how to setup unit tests using MEF.&#160; With the interface I can easily create a fake registry.</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IHandlerRegistry {
        IMediaTypeHandler GetHandler(ContentType contentType);
    }</pre>
</div>
<p>Media type handlers I will cover in more detail at a later date.&#160; All we care about for this series of articles, is that they can be used to do two things:&#160; 1) they can convert the stream of bytes coming from the http response into a class that implements IHypermediaContent and 2) they can create and run a controller with RunController(HttpResponseMessage response) method that will “do” whatever that media type is supposed to do.&#160; I realize that sounds very vague, but vague is good when we don’t want to introduce coupling <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IMediaTypeHandler {
    IHypermediaContent GetContent(HttpContent content);
    IMediaTypeController RunController(HttpResponseMessage message);
}</pre>
</div>
<p>For this article I’m going to ignore RunController and we will get to human driven clients in an upcoming article.&#160; That leaves us with GetContent that returns an IHypermediaContent interface.&#160; That interface looks like this: </p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IHypermediaContent {
       IDictionary&lt;<span class="kwrd">string</span>, Link&gt; Links { get; }
   } </pre>
</div>
<p>Not exactly complex to implement!&#160; Consider what it would take to write a handler that processes, HTML, XHTML, Atom Feeds, <a href="http://restafari.blogspot.com/2010/06/please-accept-applicationhalxml.html">HAL</a>, or even one that attempts to scrape links out of Json or generic XML based on some link convention.&#160; </p>
<h3>Magical Links</h3>
<p>Pulling this all back together, when you navigate the agent to a particular location on the web, the agent will identify the media type of the returned response, determine a handler for that media type, allow the handler to process the bytes and extra the links and store them in a dictionary available via the CurrentLinks property of the agent. </p>
<p>Here is a completely hypothetical use of the RestAgent to crawl safe links on a site: </p>
<div>
<pre class="csharpcode">var agent = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient(), <span class="kwrd">new</span> Uri(“http:<span class="rem">//mythical.com/hypermediaService”));</span>
ExploreLinks(agent);

<span class="kwrd">public</span> <span class="kwrd">void</span> ExploreLinks(RestAgent agent) {
var links = CopyLinks(agent.CurrentLinks);
<span class="kwrd">foreach</span>(Link link <span class="kwrd">in</span> links) {
    <span class="kwrd">if</span> (Link.Method == HttpMethod.GET &amp;&amp; Link.LinkRelation.RequiresParameters == <span class="kwrd">false</span>) {
        agent.NavigateTo(link);
        Explore(agent);
    }
}
}</pre>
</div>
<p>To keep things simple, I only traverse links whose LinkRelation specifies a GET is the appropriate verb and only links that do not require parameters.&#160; </p>
<p>I realize that this is still not a very useful example, but enough of the pieces are in place so that in the next article I will talk more about how to get the agent to actually do something useful. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/08/12/rest-agent-uses-hypermedia/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rest Agent &#8211; An introduction</title>
		<link>http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/</link>
		<comments>http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 11:14:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/</guid>
		<description><![CDATA[You might say I’m a bit of a fan of the REST architectural style. Let me provide a little background to clarify why REST is important to me, so you can better understand my underlying objectives.&#160; If we have similar objective then maybe this series of posts will be of interest to you. I write [...]]]></description>
			<content:encoded><![CDATA[<p>You might say I’m a bit of a fan of the REST architectural style. Let me provide a little background to clarify why REST is important to me, so you can better understand my underlying objectives.&#160; If we have similar objective then maybe this series of posts will be of interest to you.</p>
<p>I write distributed business applications for a living and to date, it appears that I end up supporting the code I write for at least 10 to 15 years.&#160; When ever you deploy and update distributed systems there is a nasty side effect of having different components to update and trying to deploy them simultaneously is rife with pitfalls.&#160; Deploying an update to a server compared with updating software on 50 client machines is just a completely different set of problems and keeping them synchronized can be challenging.&#160; </p>
<p>I realize that many people would argue that using a web browser as a client platform would solve my distribution problems.&#160; It would solve the distribution problem, but it would also introduce a whole host of other problems for the types of applications I write.&#160; Browser based apps are awesome for many things, some things they are not so awesome for.</p>
<p>The REST constraints allow you to manage the coupling between the distributed components and allow them to evolve more independently. This allows the system as a whole to evolve incrementally over long periods of time.&#160; I need this kind of robustness in my line of work. </p>
<p>In the three years that I have been building RESTful systems I have seen lots written about how to design and implement RESTful APIs but very little has been written about how REST client applications need to be written.&#160; The few people I have seen talk about it are <a href="http://www.stucharlton.com/blog/archives/2010/03/building-a-restful-hypermedia.html">Stu Charlton</a> and <a href="http://restfulie.caelumobjects.com/">Guilherme Silveira</a>.</p>
<p>This is hopefully the first in a series of blog posts where I cover what I am learning about writing client applications that are part of a RESTful distributed system.</p>
<h4>REST clients are a different breed</h4>
<p>One of the core concepts when designing a REST client is the notion of Hypermedia as the Engine of Application State.&#160; I’m not going to try and explain what I think it means, as many people far more eloquent than I, have tried and yet its meaning is still much debated.&#160; Instead, I would prefer to show some code that I believe embodies the concept.</p>
<p>My REST client applications are built around a class called RestAgent.&#160; I like to imagine my instance of the RestAgent class as little guy travelling across the web making requests and fetching data on my behalf [1].&#160; This agent is responsible for holding all of my application state and for transferring state to and from origin servers. </p>
<p>In its most simple incarnation the class looks something like:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> RestAgent(HttpClient client) {

<span class="kwrd">  private</span> Uri _CurrentLocation;
<span class="kwrd">  private</span> HttpContent_CurrentContent;

<span class="kwrd">  public</span> <span class="kwrd">void</span> NavigateTo(Uri url) {

    _CurrentContent = client.Get(url).Content;
    _CurrentLocation = url;
  }

}</pre>
<p>The RestAgent itself does not know any of the nitty gritty details of how to do HTTP interactions, so I need to provide it with some kind of Http client library.&#160; Obviously, I’ve chosen to use the Microsoft Http client, but in theory any library could work.&#160; </p>
<p>At this point the only thing that the RestAgent is really capable of doing is navigating to the provided url and retreiving the returned content.&#160; The important concept here is that at any one point in time, the RESTAgent can only be in one place.&#160; As we expand on the capabilities of the agent we will allow it to accumulate content during its travels and the aggregate of all of that content will be the “application state”, but if our client application really needs to be in multiple places at once, then we will create multiple agent instances.</p>
<p>For just a small taste of how you might use this RestAgent, </p>
<p>&#160;</p>
<div>
<pre class="csharpcode">var agent = <span class="kwrd">new</span> RestAgent(<span class="kwrd">new</span> HttpClient());

agent.NavigateTo(<span class="kwrd">new</span> Uri(“http:<span class="rem">//api.stackoverflow.com/1.0/questions”)); </span>
var questions = agent.CurrentContent.ReadAsJson();

agent.NavigateTo(“http:<span class="rem">//search.twitter.com/search.atom?q=@darrel_miller”) </span>
var mentions = agent.CurrentContent.ReadAsSyndicationFeed();</pre>
</div>
<p>&#160;</p>
<p>In the next post, I’ll talk more about hypermedia and how the agent can use links from hypermedia content to travel further and gather more content.</p>
<p>&#160;</p>
<p>&#160;</p>
<p>[1]&#160; I originally wanted to call this class AgentFielding to anthropomorphize the class even more, but it seemed a touch presumptuous <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/08/09/rest-agent-an-introduction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>But can you test it?</title>
		<link>http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/</link>
		<comments>http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 14:13:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/</guid>
		<description><![CDATA[Testing code that uses HttpWebRequest directly, is a real pain.&#160; Usually what I have seen people do is create a service interface that hides the real http client behind the interface and then create fake service implementations to actually run their tests against.&#160; The annoying part about that solution is that Http client interfaces tend [...]]]></description>
			<content:encoded><![CDATA[<p>Testing code that uses HttpWebRequest directly, is a real pain.&#160; Usually what I have seen people do is create a service interface that hides the real http client behind the interface and then create fake service implementations to actually run their tests against.&#160; The annoying part about that solution is that Http client interfaces tend to be relatively large to fake when you consider all the properties and methods of the Http request objects and http response objects.&#160; It is not inconceivable that the interface ends up exposing 90% of the functionality of the http client objects.</p>
<p>The Microsoft.Http library provides an alternative solution, assuming you don’t mind taking a dependency on it.&#160; The HttpClient class supports the notion of a pipeline of stages with one of those stages being a transport stage that actually makes the real http request.&#160; If we introduce a new stage prior to the transport stage we can intercept the request and return a response object with pre-canned values.&#160;&#160; </p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="rem">//Arrange</span>
var client = <span class="kwrd">new</span> HttpClient();
client.Stages.Add(<span class="kwrd">new</span> FixedTransport((key) =&gt; <span class="kwrd">new</span> HttpResponseMessage() {
   Content = HttpContent.Create(<span class="str">&quot;Hello World&quot;</span>)
}));

<span class="rem">//Act</span>
var  response = client.Get(<span class="str">&quot;http://example.org&quot;</span>);

<span class="rem">//Assert</span>
Assert.AreEqual(<span class="str">&quot;Hello World&quot;</span>,response.Content.ReadAsString());</pre>
</div>
<p>&#160;</p>
<p>This unit test creates a instance of the real HttpClient and adds a new processing stage called FixedTransport.&#160; This class is available in Microsoft.Http.Test and unfortunately you cannot create your own version of this class because the method that needs to be overridden to create a custom response is marked as internal.&#160; The Test dll can do it because it is pointed to by the InternalsVisibleTo attribute.&#160; The only other option is to recompile the core library yourself. <img src='http://www.bizcoder.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>The FixedTransport stage is actually derived from a caching stage that can associate a URI to particular response.&#160; In the sample above, I simply ignore the key and return the same content for all URIs.&#160; However, this mechanism would allow you to preload the cache with a set of URI/response pairs and then you could run a test that performed multiple GET requests.</p>
<p>I’m not exactly sure why but from looking through the source it does appear that if you made a non-GET request the key value would be null.&#160; That would allow you to return a specific response to a POST or PUT request based on that null key value.</p>
<p>I hope it is fairly obvious even after this very simple example that you should be able to easily generate pre-canned responses to standard http requests and still have access to the full capabilities of the HttpClient library without having to fake any classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HttpContent instead of streams</title>
		<link>http://www.bizcoder.com/index.php/2009/12/09/http-content-instead-of-streams/</link>
		<comments>http://www.bizcoder.com/index.php/2009/12/09/http-content-instead-of-streams/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 04:44:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/?p=93</guid>
		<description><![CDATA[I think the HttpContent class is my favourite part of this library.&#160; This class acts as a container for the content that you received or are about to send. Handling returned content When you do make an http request with this library, the body of the response is wrapped inside an HttpContent object. So, when [...]]]></description>
			<content:encoded><![CDATA[<p>I think the HttpContent class is my favourite part of this library.&#160; This class acts as a container for the content that you received or are about to send. </p>
<h2>Handling returned content</h2>
<p>When you do make an http request with this library, the body of the response is wrapped inside an HttpContent object. So, when you do:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var content = HttpClient.Get(“http://www.google.com”);</pre>
</div>
<p>what you get back is an HttpContent object.&#160; How you convert that into something useful, depends on what type of data the content object contains.&#160; The HttpContent.ContentType property will tell you the <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet-media-type</a> type of the data you received.</p>
<p>If you get back <code>text/plain</code> then you can access it like this,</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var mytext = content.ReadAsString();</pre>
</div>
<p>if you get application and <code>application/octet-stream</code> and you know what to do with the bytes, you can simply do</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var mybytearray = content.ReadAsByteArray();</pre>
</div>
<p>However, these examples are pretty primitive.&#160; If you reference the DLL Microsoft.Http.Extensions you will find a variety of richer data extraction methods that have been implemented as extension methods on the HttpContent class.&#160; So you can then do:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var xmlElement = content.ReadAsXElement()
var xmlReader = content.ReadAsXmlReader()</pre>
</div>
<p>to access stuff that comes to you as <code>application/xml.</code></p>
<p>One of the more sophisticated methods is ReadAsSyndicationFeed.&#160; This method leverages the RSS/Atom wrappers that are provided by WCF’s System.ServiceModel.Web DLL.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var client = <span class="kwrd">new</span> HttpClient();
var response = client.Get(<span class="str">&quot;http://www.stackoverflow.com/feeds&quot;</span>);
var feed = response.Content.ReadAsSyndicationFeed();
<span class="kwrd">foreach</span> (SyndicationItem item <span class="kwrd">in</span> feed.Items) {
    Console.WriteLine(item.Title.Text);
}</pre>
</div>
<p>This example pulls an Atom feed from the front page of Stackoverflow.com.&#160; This really shows the beauty of a standardized data format like Atom.&#160; Those few lines of code above will work in so many places across the web, and now with Microsoft pushing the new OData standard which is based on the Atom Publishing Protocol, many more of the Microsoft products will expose data in this way. e.g. Sharepoint 2010, Azure.</p>
<p>For those of you who feel the burning desire to pull custom objects across the wire, you don’t have to feel ignored as these following methods will take care of all the deserialization work and return you a nice static type.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var customer = content.ReadAsXmlSerializable&lt;Customer&gt;()
var customer = content.ReadAsDataContract&lt;Customer&gt;()</pre>
</div>
<p>and finally if you want to pull objects across the wire, but are offended by angle brackets, you can use curly braces too.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var customer = content.ReadAsJsonDataContract&lt;Customer&gt;()</pre>
</div>
<p>The use of extension methods here is really quite elegant because it makes it really easy to add your own “ReadAs” methods and use them in a completely consistent way.&#160; The fact that many of the provided extension methods are factored out into their own Dll means that you do not need to deploy that library, and you can use just your own extension methods.&#160; This has the additional benefit of allowing you to use this library without taking a dependency on WCF if you don’t want to. </p>
<p>&#160;</p>
<h2>Sending Content</h2>
<p>To send content you can use either PUT or POST and the way you prepare the content is identical.&#160; The basic process looks like this:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var client = <span class="kwrd">new</span> HttpClient()
var content = HttpContent.Create(&lt;whatever you want to send&gt;);
client.Post(content); // or client.Put(content);</pre>
<p>The only part that changes is how you create the HttpContent object.</p>
</div>
<p>Suppose you want to send some simple text</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var content = HttpContent.Create(“Here <span class="kwrd">is</span> some content”, <span class="str">&quot;text/plain&quot;</span>);</pre>
</div>
<p>or maybe just an array of bytes.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var content = HttpContent.Create(<span class="kwrd">new</span> <span class="kwrd">byte</span>[] { 1, 2, 3 }, <span class="str">&quot;application/octet-stream&quot;</span>);</pre>
</div>
<p>How about sending a file?</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var c = HttpContent.Create(<span class="kwrd">new</span> FileInfo(“myfile.zip”), <span class="str">&quot;application/octet-stream&quot;</span>);</pre>
</div>
<p>If you are dealing with an existing API that expects a POST from an html form then you will need to post using the content-type <code>application/x-www-form-urlencoded</code>.&#160; That is as easy as,</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var c = HttpContent.Create(<span class="kwrd">new</span> HttpUrlEncodedForm() { { <span class="str">&quot;a&quot;</span>, <span class="str">&quot;1&quot;</span> }, { <span class="str">&quot;b&quot;</span>, <span class="str">&quot;2&quot;</span> } });</pre>
</div>
<p>and for a more concrete example, twitter always makes a good test subject.&#160; Here is how you do a status update,</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var client = <span class="kwrd">new</span> HttpClient();
client.DefaultHeaders.Authorization = Credential.CreateBasic(<span class="str">&quot;username&quot;</span>,<span class="str">&quot;password&quot;</span>);
var form = <span class="kwrd">new</span> HttpUrlEncodedForm();
form.Add(<span class="str">&quot;status&quot;</span>,<span class="str">&quot;Test tweet using Microsoft.Http.HttpClient&quot;</span>);
var content = HttpContent.Create(form);
var resp = client.Post(<span class="str">&quot;http://www.twitter.com/statuses/update.xml&quot;</span>, content);</pre>
</div>
<p>&#160;</p>
<p>It is pretty easy to continue this pattern and create your own factory methods for converting your favourite data type into an HttpContent object.&#160; There are are quite a few other nice features about the content object relating to how it manages the underlying stream, when it reads from the stream, if it buffers the stream and other such nitty gritty, but I’ll save those details for another day.&#160; To keep track of the other articles I am attempting to write on the subject, you can see the summary post <a href="http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2009/12/09/http-content-instead-of-streams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HttpClient – The basics</title>
		<link>http://www.bizcoder.com/index.php/2009/12/08/httpclient-the-basics/</link>
		<comments>http://www.bizcoder.com/index.php/2009/12/08/httpclient-the-basics/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 03:16:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2009/12/08/httpclient-the-basics/</guid>
		<description><![CDATA[Before I go into any details I thought it would be valuable to give some basic examples of how to use the HTTPClient. Retrieve some HTTP content from an URL var client = new HttpClient(); var response = client.Get(&#34;http://example.org&#34;); Post some content to an Url var client = new HttpClient(); var content = HttpContent.Create(&#34;This is [...]]]></description>
			<content:encoded><![CDATA[<p>Before I go into any details I thought it would be valuable to give some basic examples of how to use the HTTPClient.</p>
<p>Retrieve some HTTP content from an URL</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var client = <span class="kwrd">new</span> HttpClient();
var response = client.Get(<span class="str">&quot;http://example.org&quot;</span>);</pre>
</div>
<p>Post some content to an Url</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var client = <span class="kwrd">new</span> HttpClient();
var content = HttpContent.Create(<span class="str">&quot;This is some string content&quot;</span>);
var response = client.Post(<span class="str">&quot;http://example.com&quot;</span>, content);</pre>
</div>
<p>Authenticated get</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var client = <span class="kwrd">new</span> HttpClient();
client.DefaultHeaders.Authorization = Credential.CreateBasic(<span class="str">&quot;user&quot;</span>, <span class="str">&quot;password&quot;</span>);
var response = client.Get(<span class="str">&quot;http://example.org&quot;</span>);</pre>
</div>
<p>and if you need to provide some kind of custom authentication scheme you can simply create credential like this</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">client.DefaultHeaders.Authorization = <span class="kwrd">new</span> Credential(“My secure authentication header”);</pre>
<pre class="csharpcode">&#160;</pre>
</div>
<p>Interestingly, the methods Get and Post are not actually members of the HttpClient class.&#160; They are extension methods that simply call one of the Send methods on the HttpClient class.&#160; If it is more appropriate you can also call the Send methods directly. As you will see, there are plenty of overloads to suit your needs:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode"><span class="kwrd"></span>&#160;</pre>
<pre class="csharpcode"><span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, Uri uri)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, Uri uri, RequestHeaders headers)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, Uri uri, HttpContent content)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, <span class="kwrd">string</span> uri)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, <span class="kwrd">string</span> uri, RequestHeaders headers)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, <span class="kwrd">string</span> uri, HttpContent content)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, <span class="kwrd">string</span> uri, RequestHeaders headers, HttpContent content)
<span class="kwrd">public</span> HttpResponseMessage Send(HttpMethod method, Uri uri, RequestHeaders headers, HttpContent content)</pre>
<pre class="csharpcode">&#160;</pre>
</div>
<p>I like this approach because it provides a host of easy to call helper methods that are all routed through one of these Send methods.&#160; </p>
<p>Another major advantage of the HttpClient library over the HttpWebRequest class is related to the RequestHeaders class.&#160; All of the Http header values have been wrapped with some kind of helper class that significantly eases the process of setthing header values.</p>
<p>Here are a few random examples of setting header information that pulled from the unit tests:</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var req = <span class="kwrd">new</span> RequestHeaders();
req.Accept.Add(StringWithOptionalQuality.Parse(<span class="str">&quot;audio/*; q=0.2&quot;</span>));

req.Allow.Add(<span class="str">&quot;GET&quot;</span>);
req.Allow.Add(<span class="str">&quot;POST&quot;</span>); 

var cc = <span class="kwrd">new</span> CacheControl();
cc.MaxAge = TimeSpan.FromSeconds(1);
cc.MaxStale = <span class="kwrd">true</span>;
cc.MaxStaleLimit = TimeSpan.FromSeconds(2);
cc.MinFresh = TimeSpan.FromSeconds(3);
cc.MustRevalidate = <span class="kwrd">true</span>;
cc.NoCache = <span class="kwrd">true</span>;

req.CacheControl = cc;</pre>
</div>
<p>In addition to these headers that have strongly typed classes there is also the nifty Parse() function that is on both the request and response header collections.</p>
<div class="csharpcode-wrapper">
<pre class="csharpcode">var h = RequestHeaders.Parse(<span class="str">&quot;Pragma: LinkBW=2147483647, AccelBW=1048576, AccelDuration=5000&quot;</span>); 

var resp = ResponseHeaders.Parse(
                <span class="str">@&quot;Set-Cookie: mkt1=norm=US; domain=.live.com; path=/
                    Set-Cookie: AFORM=NOFORM; expires=Mon, 20-Jul-2015 23:59:59 GMT; path=/&quot;</span>.Trim());

var h = RequestHeaders.Parse(
               <span class="str">@&quot;Accept-Charset: iso-8859-5, unicode-1-1;q=0.8
           Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0
           Accept-Language: da, en-gb;q=0.8, en;q=0.7&quot;</span>);

var h = ResponseHeaders.Parse(<span class="str">@&quot;WWW-Authenticate: Digest realm=&quot;</span><span class="str">&quot;testrealm@host.com&quot;</span><span class="str">&quot;,
                qop=&quot;</span><span class="str">&quot;auth,auth-int&quot;</span><span class="str">&quot;,
                nonce=&quot;</span><span class="str">&quot;dcd98b7102dd2f0e8b11d0f600bfb0c093&quot;</span><span class="str">&quot;,
                opaque=&quot;</span><span class="str">&quot;5ccc069c403ebaf9f0171e9517f40e41&quot;</span><span class="str">&quot;&quot;</span>);</pre>
</div>
<p>Who wants to write and test the code necessary to parse this stuff?&#160; Not me, that’s for sure. Hopefully this has provided a taste for what this library is capable of and over the next few weeks I plan on writing a number of other posts that cover other interesting areas of the Microsoft.Http namespace.&#160; To see where I am up to, see the summary page <a href="http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2009/12/08/httpclient-the-basics/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why the Microsoft.Http library is awesome.</title>
		<link>http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/</link>
		<comments>http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 03:15:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/</guid>
		<description><![CDATA[In various forums I a finding myself raving about this new library.&#160; I decided that I should write some blog posts on the subject for a few reasons.&#160; 1) to convince myself that there is actually some substance to my raving; 2) provide a place to point people to in order to substantiate my infatuation [...]]]></description>
			<content:encoded><![CDATA[<p>In various forums I a finding myself raving about this new library.&#160; I decided that I should write some blog posts on the subject for a few reasons.&#160; 1) to convince myself that there is actually some substance to my raving; 2) provide a place to point people to in order to substantiate my infatuation and 3) maybe encourage a few more people to use it before it gets relegated to the dustbin of Microsoft’s forgotten projects.</p>
<p>Here are the posts I am planning.&#160; I will create the links as the posts are completed.</p>
<ul>
<li><a href="http://www.bizcoder.com/index.php/2009/12/08/httpclient-the-basics/">The basics</a> </li>
<li><a href="http://www.bizcoder.com/index.php/2009/12/09/http-content-instead-of-streams/">HttpContent instead of streams</a> </li>
<li><a href="http://www.bizcoder.com/index.php/2010/02/12/but-can-you-test-it/">But can you test it</a>? </li>
<li>HttpClient on the server </li>
</ul>
<p>You can get the library <a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644">here</a> and the official support forum is <a href="http://forums.asp.net/1180.aspx">here</a>.&#160; From what I have been told, this library will not make it into the .Net 4 release but it is still being actively developed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2009/12/08/why-the-microsoft-http-library-is-awesome/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WCF REST Starter Kit Preview 2</title>
		<link>http://www.bizcoder.com/index.php/2009/03/14/wcf-rest-starter-kit-preview-2/</link>
		<comments>http://www.bizcoder.com/index.php/2009/03/14/wcf-rest-starter-kit-preview-2/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 00:30:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTPClient]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.bizcoder.com/index.php/2009/03/14/wcf-rest-starter-kit-preview-2/</guid>
		<description><![CDATA[I have been looking thought the latest release of the WCF REST Starter Kit and there are some interesting things there.&#160; Especially the new HttpClient class in the Microsoft.Http namespace.&#160; I will not talk about the server side of things because I really don&#8217;t have anything nice to say and until I have some constructive [...]]]></description>
			<content:encoded><![CDATA[<p>I have been looking thought the latest release of the WCF REST Starter Kit and there are some interesting things there.&nbsp; Especially the new HttpClient class in the Microsoft.Http namespace.&nbsp; I will not talk about the server side of things because I really don&#8217;t have anything nice to say and until I have some constructive criticism to give I&#8217;m going to keep my mouth shut.</p>
<p>However, the new client side library is designed to make it easier to talk to HTTP endpoints and it seems to be quite nice.&nbsp; It is 3500 lines of code, so there is a fair bit of stuff in there, layered on top of HttpWebRequest and I was curious to see what it could do.</p>
<p>I started by looking at the enclosed sample, unhelpfully named &#8220;WpfSample&#8221; and I got a little sidetracked from my exploration.&nbsp; This sample is actually a very neat little http request builder tool.&nbsp; I know this is a cool tool to have, because I have an almost identical one that we built to help us test REST services.&nbsp; Testing with real web browsers is really annoying because they do all sorts of magic stuff behind the scenes, they are very picky about what content-types they will render and they keep trying to find a favicon!&nbsp; </p>
<p>Anyway, I was curious to see how this tool made use of the HttpClient class but I was rather dismayed to see <strong>all</strong> of the code in the &#8220;code behind&#8221; of the Window1.xaml file.&nbsp; This makes it really difficult to distinguish between what code is relevant to the web request and what is just UI gunk.&nbsp; To add salt to the wound, it is a WPF app that uses no data binding and no Commands, just events manipulating the contents of UI elements.&nbsp; It was a nice looking, handy WPF app that demonstrated this new spiffy HttpClient library with the architecture of a college student&#8217;s VB4 project.</p>
<p>Ok, I know it is just a sample.&nbsp; However, everything that Microsoft puts out is viewed by people who are learning.&nbsp; If Microsoft create samples with crappy architecture, why are we surprised when developers create applications with crappy architectures.</p>
<p>So despite the ton of work that I was supposed to be doing today, I refactored it.&nbsp; I created an MVC type of structure with databinding and routed commands.&nbsp; If you get the <a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644">WCF REST Starter Kit</a> and extract the zip file that gets put in the &#8220;C:\Program Files (x86)\Microsoft WCF REST&#8221; folder you will find a solution named Product.sln.&nbsp; Just add my project which is in the zip file below and you will have, what I hope is a much easier to read version of the HttpClient sample.</p>
<p><a href="http://www.tavis.ca/files/httpClientGui.zip">http://www.tavis.ca/files/httpClientGui.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bizcoder.com/index.php/2009/03/14/wcf-rest-starter-kit-preview-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
